Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/filelock-3.13.4.dist-info/INSTALLER +1 -0
- env-llmeval/lib/python3.10/site-packages/filelock-3.13.4.dist-info/METADATA +56 -0
- env-llmeval/lib/python3.10/site-packages/filelock-3.13.4.dist-info/licenses/LICENSE +24 -0
- env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/INSTALLER +1 -0
- env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/LICENSE +19 -0
- env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/METADATA +259 -0
- env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/RECORD +15 -0
- env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/WHEEL +4 -0
- env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/INSTALLER +1 -0
- env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/LICENSE +27 -0
- env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/METADATA +233 -0
- env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/RECORD +180 -0
- env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/WHEEL +5 -0
- env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/top_level.txt +1 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/take.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/tools/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/tools/timedeltas.py +283 -0
- env-llmeval/lib/python3.10/site-packages/pandas/core/tools/times.py +168 -0
- env-llmeval/lib/python3.10/site-packages/psutil/__init__.py +2492 -0
- env-llmeval/lib/python3.10/site-packages/psutil/__pycache__/_psosx.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_common.py +983 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_compat.py +483 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_psaix.py +582 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_psbsd.py +977 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_pslinux.py +2366 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_psosx.py +555 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_psposix.py +243 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_pssunos.py +756 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_psutil_linux.abi3.so +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_psutil_posix.abi3.so +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/_pswindows.py +1170 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__init__.py +2043 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__main__.py +12 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/runner.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_bsd.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_connections.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_contracts.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_linux.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_memleaks.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_osx.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_posix.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process_all.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_system.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/filelock-3.13.4.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
env-llmeval/lib/python3.10/site-packages/filelock-3.13.4.dist-info/METADATA
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.3
|
2 |
+
Name: filelock
|
3 |
+
Version: 3.13.4
|
4 |
+
Summary: A platform independent file lock.
|
5 |
+
Project-URL: Documentation, https://py-filelock.readthedocs.io
|
6 |
+
Project-URL: Homepage, https://github.com/tox-dev/py-filelock
|
7 |
+
Project-URL: Source, https://github.com/tox-dev/py-filelock
|
8 |
+
Project-URL: Tracker, https://github.com/tox-dev/py-filelock/issues
|
9 |
+
Maintainer-email: Bernát Gábor <[email protected]>
|
10 |
+
License-Expression: Unlicense
|
11 |
+
License-File: LICENSE
|
12 |
+
Keywords: application,cache,directory,log,user
|
13 |
+
Classifier: Development Status :: 5 - Production/Stable
|
14 |
+
Classifier: Intended Audience :: Developers
|
15 |
+
Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
|
16 |
+
Classifier: Operating System :: OS Independent
|
17 |
+
Classifier: Programming Language :: Python
|
18 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
19 |
+
Classifier: Programming Language :: Python :: 3.8
|
20 |
+
Classifier: Programming Language :: Python :: 3.9
|
21 |
+
Classifier: Programming Language :: Python :: 3.10
|
22 |
+
Classifier: Programming Language :: Python :: 3.11
|
23 |
+
Classifier: Programming Language :: Python :: 3.12
|
24 |
+
Classifier: Topic :: Internet
|
25 |
+
Classifier: Topic :: Software Development :: Libraries
|
26 |
+
Classifier: Topic :: System
|
27 |
+
Requires-Python: >=3.8
|
28 |
+
Provides-Extra: docs
|
29 |
+
Requires-Dist: furo>=2023.9.10; extra == 'docs'
|
30 |
+
Requires-Dist: sphinx-autodoc-typehints!=1.23.4,>=1.25.2; extra == 'docs'
|
31 |
+
Requires-Dist: sphinx>=7.2.6; extra == 'docs'
|
32 |
+
Provides-Extra: testing
|
33 |
+
Requires-Dist: covdefaults>=2.3; extra == 'testing'
|
34 |
+
Requires-Dist: coverage>=7.3.2; extra == 'testing'
|
35 |
+
Requires-Dist: diff-cover>=8.0.1; extra == 'testing'
|
36 |
+
Requires-Dist: pytest-cov>=4.1; extra == 'testing'
|
37 |
+
Requires-Dist: pytest-mock>=3.12; extra == 'testing'
|
38 |
+
Requires-Dist: pytest-timeout>=2.2; extra == 'testing'
|
39 |
+
Requires-Dist: pytest>=7.4.3; extra == 'testing'
|
40 |
+
Provides-Extra: typing
|
41 |
+
Requires-Dist: typing-extensions>=4.8; (python_version < '3.11') and extra == 'typing'
|
42 |
+
Description-Content-Type: text/markdown
|
43 |
+
|
44 |
+
# filelock
|
45 |
+
|
46 |
+
[](https://pypi.org/project/filelock/)
|
47 |
+
[](https://pypi.org/project/filelock/)
|
49 |
+
[](https://py-filelock.readthedocs.io/en/latest/?badge=latest)
|
51 |
+
[](https://github.com/psf/black)
|
53 |
+
[](https://pepy.tech/project/filelock)
|
54 |
+
[](https://github.com/tox-dev/py-filelock/actions/workflows/check.yml)
|
55 |
+
|
56 |
+
For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).
|
env-llmeval/lib/python3.10/site-packages/filelock-3.13.4.dist-info/licenses/LICENSE
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
This is free and unencumbered software released into the public domain.
|
2 |
+
|
3 |
+
Anyone is free to copy, modify, publish, use, compile, sell, or
|
4 |
+
distribute this software, either in source code form or as a compiled
|
5 |
+
binary, for any purpose, commercial or non-commercial, and by any
|
6 |
+
means.
|
7 |
+
|
8 |
+
In jurisdictions that recognize copyright laws, the author or authors
|
9 |
+
of this software dedicate any and all copyright interest in the
|
10 |
+
software to the public domain. We make this dedication for the benefit
|
11 |
+
of the public at large and to the detriment of our heirs and
|
12 |
+
successors. We intend this dedication to be an overt act of
|
13 |
+
relinquishment in perpetuity of all present and future rights to this
|
14 |
+
software under copyright law.
|
15 |
+
|
16 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
17 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
18 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
19 |
+
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
20 |
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
21 |
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
22 |
+
OTHER DEALINGS IN THE SOFTWARE.
|
23 |
+
|
24 |
+
For more information, please refer to <http://unlicense.org>
|
env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/LICENSE
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2012 Erik Rose
|
2 |
+
|
3 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
this software and associated documentation files (the "Software"), to deal in
|
5 |
+
the Software without restriction, including without limitation the rights to
|
6 |
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
7 |
+
of the Software, and to permit persons to whom the Software is furnished to do
|
8 |
+
so, subject to the following conditions:
|
9 |
+
|
10 |
+
The above copyright notice and this permission notice shall be included in all
|
11 |
+
copies or substantial portions of the Software.
|
12 |
+
|
13 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
SOFTWARE.
|
env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/METADATA
ADDED
@@ -0,0 +1,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
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: more-itertools
|
3 |
+
Version: 10.2.0
|
4 |
+
Summary: More routines for operating on iterables, beyond itertools
|
5 |
+
Keywords: itertools,iterator,iteration,filter,peek,peekable,chunk,chunked
|
6 |
+
Author-email: Erik Rose <[email protected]>
|
7 |
+
Requires-Python: >=3.8
|
8 |
+
Description-Content-Type: text/x-rst
|
9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
10 |
+
Classifier: Intended Audience :: Developers
|
11 |
+
Classifier: Natural Language :: English
|
12 |
+
Classifier: License :: OSI Approved :: MIT License
|
13 |
+
Classifier: Programming Language :: Python :: 3
|
14 |
+
Classifier: Programming Language :: Python :: 3.8
|
15 |
+
Classifier: Programming Language :: Python :: 3.9
|
16 |
+
Classifier: Programming Language :: Python :: 3.10
|
17 |
+
Classifier: Programming Language :: Python :: 3.11
|
18 |
+
Classifier: Programming Language :: Python :: 3.12
|
19 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
20 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
21 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
22 |
+
Classifier: Topic :: Software Development :: Libraries
|
23 |
+
Project-URL: Homepage, https://github.com/more-itertools/more-itertools
|
24 |
+
|
25 |
+
==============
|
26 |
+
More Itertools
|
27 |
+
==============
|
28 |
+
|
29 |
+
.. image:: https://readthedocs.org/projects/more-itertools/badge/?version=latest
|
30 |
+
:target: https://more-itertools.readthedocs.io/en/stable/
|
31 |
+
|
32 |
+
Python's ``itertools`` library is a gem - you can compose elegant solutions
|
33 |
+
for a variety of problems with the functions it provides. In ``more-itertools``
|
34 |
+
we collect additional building blocks, recipes, and routines for working with
|
35 |
+
Python iterables.
|
36 |
+
|
37 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
38 |
+
| Grouping | `chunked <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.chunked>`_, |
|
39 |
+
| | `ichunked <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ichunked>`_, |
|
40 |
+
| | `chunked_even <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.chunked_even>`_, |
|
41 |
+
| | `sliced <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sliced>`_, |
|
42 |
+
| | `constrained_batches <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.constrained_batches>`_, |
|
43 |
+
| | `distribute <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distribute>`_, |
|
44 |
+
| | `divide <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.divide>`_, |
|
45 |
+
| | `split_at <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_at>`_, |
|
46 |
+
| | `split_before <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_before>`_, |
|
47 |
+
| | `split_after <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_after>`_, |
|
48 |
+
| | `split_into <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_into>`_, |
|
49 |
+
| | `split_when <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_when>`_, |
|
50 |
+
| | `bucket <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.bucket>`_, |
|
51 |
+
| | `unzip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unzip>`_, |
|
52 |
+
| | `batched <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.batched>`_, |
|
53 |
+
| | `grouper <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.grouper>`_, |
|
54 |
+
| | `partition <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partition>`_, |
|
55 |
+
| | `transpose <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.transpose>`_ |
|
56 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
57 |
+
| Lookahead and lookback | `spy <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.spy>`_, |
|
58 |
+
| | `peekable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.peekable>`_, |
|
59 |
+
| | `seekable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.seekable>`_ |
|
60 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
61 |
+
| Windowing | `windowed <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.windowed>`_, |
|
62 |
+
| | `substrings <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.substrings>`_, |
|
63 |
+
| | `substrings_indexes <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.substrings_indexes>`_, |
|
64 |
+
| | `stagger <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.stagger>`_, |
|
65 |
+
| | `windowed_complete <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.windowed_complete>`_, |
|
66 |
+
| | `pairwise <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.pairwise>`_, |
|
67 |
+
| | `triplewise <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.triplewise>`_, |
|
68 |
+
| | `sliding_window <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sliding_window>`_, |
|
69 |
+
| | `subslices <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.subslices>`_ |
|
70 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
71 |
+
| Augmenting | `count_cycle <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.count_cycle>`_, |
|
72 |
+
| | `intersperse <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.intersperse>`_, |
|
73 |
+
| | `padded <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.padded>`_, |
|
74 |
+
| | `repeat_each <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeat_each>`_, |
|
75 |
+
| | `mark_ends <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.mark_ends>`_, |
|
76 |
+
| | `repeat_last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeat_last>`_, |
|
77 |
+
| | `adjacent <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.adjacent>`_, |
|
78 |
+
| | `groupby_transform <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.groupby_transform>`_, |
|
79 |
+
| | `pad_none <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.pad_none>`_, |
|
80 |
+
| | `ncycles <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ncycles>`_ |
|
81 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
82 |
+
| Combining | `collapse <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.collapse>`_, |
|
83 |
+
| | `sort_together <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sort_together>`_, |
|
84 |
+
| | `interleave <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave>`_, |
|
85 |
+
| | `interleave_longest <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave_longest>`_, |
|
86 |
+
| | `interleave_evenly <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave_evenly>`_, |
|
87 |
+
| | `zip_offset <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_offset>`_, |
|
88 |
+
| | `zip_equal <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_equal>`_, |
|
89 |
+
| | `zip_broadcast <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_broadcast>`_, |
|
90 |
+
| | `dotproduct <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.dotproduct>`_, |
|
91 |
+
| | `convolve <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.convolve>`_, |
|
92 |
+
| | `flatten <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.flatten>`_, |
|
93 |
+
| | `roundrobin <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.roundrobin>`_, |
|
94 |
+
| | `prepend <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.prepend>`_, |
|
95 |
+
| | `value_chain <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.value_chain>`_, |
|
96 |
+
| | `partial_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partial_product>`_ |
|
97 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
98 |
+
| Summarizing | `ilen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ilen>`_, |
|
99 |
+
| | `unique_to_each <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_to_each>`_, |
|
100 |
+
| | `sample <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sample>`_, |
|
101 |
+
| | `consecutive_groups <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consecutive_groups>`_, |
|
102 |
+
| | `run_length <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.run_length>`_, |
|
103 |
+
| | `map_reduce <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_reduce>`_, |
|
104 |
+
| | `exactly_n <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.exactly_n>`_, |
|
105 |
+
| | `is_sorted <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.is_sorted>`_, |
|
106 |
+
| | `all_equal <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.all_equal>`_, |
|
107 |
+
| | `all_unique <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.all_unique>`_, |
|
108 |
+
| | `minmax <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.minmax>`_, |
|
109 |
+
| | `first_true <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first_true>`_, |
|
110 |
+
| | `quantify <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.quantify>`_, |
|
111 |
+
| | `iequals <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iequals>`_ |
|
112 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
113 |
+
| Selecting | `islice_extended <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.islice_extended>`_, |
|
114 |
+
| | `first <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first>`_, |
|
115 |
+
| | `last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.last>`_, |
|
116 |
+
| | `one <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.one>`_, |
|
117 |
+
| | `only <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.only>`_, |
|
118 |
+
| | `strictly_n <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.strictly_n>`_, |
|
119 |
+
| | `strip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.strip>`_, |
|
120 |
+
| | `lstrip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.lstrip>`_, |
|
121 |
+
| | `rstrip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.rstrip>`_, |
|
122 |
+
| | `filter_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.filter_except>`_, |
|
123 |
+
| | `map_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_except>`_, |
|
124 |
+
| | `filter_map <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.filter_map>`_, |
|
125 |
+
| | `iter_suppress <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_suppress>`_, |
|
126 |
+
| | `nth_or_last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_or_last>`_, |
|
127 |
+
| | `unique_in_window <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_in_window>`_, |
|
128 |
+
| | `before_and_after <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.before_and_after>`_, |
|
129 |
+
| | `nth <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth>`_, |
|
130 |
+
| | `take <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.take>`_, |
|
131 |
+
| | `tail <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.tail>`_, |
|
132 |
+
| | `unique_everseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_everseen>`_, |
|
133 |
+
| | `unique_justseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_justseen>`_, |
|
134 |
+
| | `duplicates_everseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.duplicates_everseen>`_, |
|
135 |
+
| | `duplicates_justseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.duplicates_justseen>`_, |
|
136 |
+
| | `classify_unique <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.classify_unique>`_, |
|
137 |
+
| | `longest_common_prefix <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.longest_common_prefix>`_, |
|
138 |
+
| | `takewhile_inclusive <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.takewhile_inclusive>`_ |
|
139 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
140 |
+
| Combinatorics | `distinct_permutations <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distinct_permutations>`_, |
|
141 |
+
| | `distinct_combinations <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distinct_combinations>`_, |
|
142 |
+
| | `circular_shifts <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.circular_shifts>`_, |
|
143 |
+
| | `partitions <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partitions>`_, |
|
144 |
+
| | `set_partitions <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.set_partitions>`_, |
|
145 |
+
| | `product_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.product_index>`_, |
|
146 |
+
| | `combination_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.combination_index>`_, |
|
147 |
+
| | `permutation_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.permutation_index>`_, |
|
148 |
+
| | `combination_with_replacement_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.combination_with_replacement_index>`_, |
|
149 |
+
| | `gray_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.gray_product>`_, |
|
150 |
+
| | `outer_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.outer_product>`_, |
|
151 |
+
| | `powerset <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.powerset>`_, |
|
152 |
+
| | `random_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_product>`_, |
|
153 |
+
| | `random_permutation <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_permutation>`_, |
|
154 |
+
| | `random_combination <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_combination>`_, |
|
155 |
+
| | `random_combination_with_replacement <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_combination_with_replacement>`_, |
|
156 |
+
| | `nth_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_product>`_, |
|
157 |
+
| | `nth_permutation <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_permutation>`_, |
|
158 |
+
| | `nth_combination <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_combination>`_, |
|
159 |
+
| | `nth_combination_with_replacement <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_combination_with_replacement>`_ |
|
160 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
161 |
+
| Wrapping | `always_iterable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable>`_, |
|
162 |
+
| | `always_reversible <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_reversible>`_, |
|
163 |
+
| | `countable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.countable>`_, |
|
164 |
+
| | `consumer <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consumer>`_, |
|
165 |
+
| | `with_iter <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.with_iter>`_, |
|
166 |
+
| | `iter_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_except>`_ |
|
167 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
168 |
+
| Others | `locate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.locate>`_, |
|
169 |
+
| | `rlocate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.rlocate>`_, |
|
170 |
+
| | `replace <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.replace>`_, |
|
171 |
+
| | `numeric_range <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.numeric_range>`_, |
|
172 |
+
| | `side_effect <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.side_effect>`_, |
|
173 |
+
| | `iterate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iterate>`_, |
|
174 |
+
| | `difference <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.difference>`_, |
|
175 |
+
| | `make_decorator <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.make_decorator>`_, |
|
176 |
+
| | `SequenceView <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.SequenceView>`_, |
|
177 |
+
| | `time_limited <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.time_limited>`_, |
|
178 |
+
| | `map_if <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_if>`_, |
|
179 |
+
| | `iter_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_index>`_, |
|
180 |
+
| | `consume <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consume>`_, |
|
181 |
+
| | `tabulate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.tabulate>`_, |
|
182 |
+
| | `repeatfunc <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeatfunc>`_, |
|
183 |
+
| | `polynomial_from_roots <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_from_roots>`_, |
|
184 |
+
| | `polynomial_eval <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_eval>`_, |
|
185 |
+
| | `polynomial_derivative <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_derivative>`_, |
|
186 |
+
| | `sieve <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sieve>`_, |
|
187 |
+
| | `factor <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.factor>`_, |
|
188 |
+
| | `matmul <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.matmul>`_, |
|
189 |
+
| | `sum_of_squares <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sum_of_squares>`_, |
|
190 |
+
| | `totient <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.totient>`_, |
|
191 |
+
| | `reshape <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.reshape>`_ |
|
192 |
+
+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
193 |
+
|
194 |
+
|
195 |
+
Getting started
|
196 |
+
===============
|
197 |
+
|
198 |
+
To get started, install the library with `pip <https://pip.pypa.io/en/stable/>`_:
|
199 |
+
|
200 |
+
.. code-block:: shell
|
201 |
+
|
202 |
+
pip install more-itertools
|
203 |
+
|
204 |
+
The recipes from the `itertools docs <https://docs.python.org/3/library/itertools.html#itertools-recipes>`_
|
205 |
+
are included in the top-level package:
|
206 |
+
|
207 |
+
.. code-block:: python
|
208 |
+
|
209 |
+
>>> from more_itertools import flatten
|
210 |
+
>>> iterable = [(0, 1), (2, 3)]
|
211 |
+
>>> list(flatten(iterable))
|
212 |
+
[0, 1, 2, 3]
|
213 |
+
|
214 |
+
Several new recipes are available as well:
|
215 |
+
|
216 |
+
.. code-block:: python
|
217 |
+
|
218 |
+
>>> from more_itertools import chunked
|
219 |
+
>>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8]
|
220 |
+
>>> list(chunked(iterable, 3))
|
221 |
+
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
|
222 |
+
|
223 |
+
>>> from more_itertools import spy
|
224 |
+
>>> iterable = (x * x for x in range(1, 6))
|
225 |
+
>>> head, iterable = spy(iterable, n=3)
|
226 |
+
>>> list(head)
|
227 |
+
[1, 4, 9]
|
228 |
+
>>> list(iterable)
|
229 |
+
[1, 4, 9, 16, 25]
|
230 |
+
|
231 |
+
|
232 |
+
|
233 |
+
For the full listing of functions, see the `API documentation <https://more-itertools.readthedocs.io/en/stable/api.html>`_.
|
234 |
+
|
235 |
+
|
236 |
+
Links elsewhere
|
237 |
+
===============
|
238 |
+
|
239 |
+
Blog posts about ``more-itertools``:
|
240 |
+
|
241 |
+
* `Yo, I heard you like decorators <https://www.bbayles.com/index/decorator_factory>`__
|
242 |
+
* `Tour of Python Itertools <https://martinheinz.dev/blog/16>`__ (`Alternate <https://dev.to/martinheinz/tour-of-python-itertools-4122>`__)
|
243 |
+
* `Real-World Python More Itertools <https://www.gidware.com/real-world-more-itertools/>`_
|
244 |
+
|
245 |
+
|
246 |
+
Development
|
247 |
+
===========
|
248 |
+
|
249 |
+
``more-itertools`` is maintained by `@erikrose <https://github.com/erikrose>`_
|
250 |
+
and `@bbayles <https://github.com/bbayles>`_, with help from `many others <https://github.com/more-itertools/more-itertools/graphs/contributors>`_.
|
251 |
+
If you have a problem or suggestion, please file a bug or pull request in this
|
252 |
+
repository. Thanks for contributing!
|
253 |
+
|
254 |
+
|
255 |
+
Version History
|
256 |
+
===============
|
257 |
+
|
258 |
+
The version history can be found in `documentation <https://more-itertools.readthedocs.io/en/stable/versions.html>`_.
|
259 |
+
|
env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/RECORD
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
more_itertools-10.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
more_itertools-10.2.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053
|
3 |
+
more_itertools-10.2.0.dist-info/METADATA,sha256=lTIPxfD4IiP6aHzPjP4dXmzRRUmiXicAB6qnY82T-Gs,34886
|
4 |
+
more_itertools-10.2.0.dist-info/RECORD,,
|
5 |
+
more_itertools-10.2.0.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81
|
6 |
+
more_itertools/__init__.py,sha256=VodgFyRJvpnHbAMgseYRiP7r928FFOAakmQrl6J88os,149
|
7 |
+
more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43
|
8 |
+
more_itertools/__pycache__/__init__.cpython-310.pyc,,
|
9 |
+
more_itertools/__pycache__/more.cpython-310.pyc,,
|
10 |
+
more_itertools/__pycache__/recipes.cpython-310.pyc,,
|
11 |
+
more_itertools/more.py,sha256=jYdpbgXHf8yZDByPrhluxpe0D_IXRk2tfQnyfOFMi74,143045
|
12 |
+
more_itertools/more.pyi,sha256=KTHYeqr0rFbn1GWRnv0jY64JRNnKKT0kA3kmsah8DYQ,21044
|
13 |
+
more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
14 |
+
more_itertools/recipes.py,sha256=Rb3OhzJTCn2biutDEUSImbuY-8NDS1lkHt0My-uCOf4,27548
|
15 |
+
more_itertools/recipes.pyi,sha256=T1IuEVXCqw2NeJJNW036MtWi8BVfR8Ilpf7cBmvhBaQ,4436
|
env-llmeval/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/WHEEL
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: flit 3.8.0
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/LICENSE
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2005-2021 Fredrik Johansson and mpmath contributors
|
2 |
+
|
3 |
+
All rights reserved.
|
4 |
+
|
5 |
+
Redistribution and use in source and binary forms, with or without
|
6 |
+
modification, are permitted provided that the following conditions are met:
|
7 |
+
|
8 |
+
a. Redistributions of source code must retain the above copyright notice,
|
9 |
+
this list of conditions and the following disclaimer.
|
10 |
+
b. Redistributions in binary form must reproduce the above copyright
|
11 |
+
notice, this list of conditions and the following disclaimer in the
|
12 |
+
documentation and/or other materials provided with the distribution.
|
13 |
+
c. Neither the name of the copyright holder nor the names of its
|
14 |
+
contributors may be used to endorse or promote products derived
|
15 |
+
from this software without specific prior written permission.
|
16 |
+
|
17 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
18 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
19 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
20 |
+
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
|
21 |
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
22 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
23 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
24 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
+
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
26 |
+
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
|
27 |
+
DAMAGE.
|
env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/METADATA
ADDED
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: mpmath
|
3 |
+
Version: 1.3.0
|
4 |
+
Summary: Python library for arbitrary-precision floating-point arithmetic
|
5 |
+
Home-page: http://mpmath.org/
|
6 |
+
Author: Fredrik Johansson
|
7 |
+
Author-email: [email protected]
|
8 |
+
License: BSD
|
9 |
+
Project-URL: Source, https://github.com/fredrik-johansson/mpmath
|
10 |
+
Project-URL: Tracker, https://github.com/fredrik-johansson/mpmath/issues
|
11 |
+
Project-URL: Documentation, http://mpmath.org/doc/current/
|
12 |
+
Classifier: License :: OSI Approved :: BSD License
|
13 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
14 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
15 |
+
Classifier: Programming Language :: Python
|
16 |
+
Classifier: Programming Language :: Python :: 2
|
17 |
+
Classifier: Programming Language :: Python :: 2.7
|
18 |
+
Classifier: Programming Language :: Python :: 3
|
19 |
+
Classifier: Programming Language :: Python :: 3.5
|
20 |
+
Classifier: Programming Language :: Python :: 3.6
|
21 |
+
Classifier: Programming Language :: Python :: 3.7
|
22 |
+
Classifier: Programming Language :: Python :: 3.8
|
23 |
+
Classifier: Programming Language :: Python :: 3.9
|
24 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
25 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
26 |
+
License-File: LICENSE
|
27 |
+
Provides-Extra: develop
|
28 |
+
Requires-Dist: pytest (>=4.6) ; extra == 'develop'
|
29 |
+
Requires-Dist: pycodestyle ; extra == 'develop'
|
30 |
+
Requires-Dist: pytest-cov ; extra == 'develop'
|
31 |
+
Requires-Dist: codecov ; extra == 'develop'
|
32 |
+
Requires-Dist: wheel ; extra == 'develop'
|
33 |
+
Provides-Extra: docs
|
34 |
+
Requires-Dist: sphinx ; extra == 'docs'
|
35 |
+
Provides-Extra: gmpy
|
36 |
+
Requires-Dist: gmpy2 (>=2.1.0a4) ; (platform_python_implementation != "PyPy") and extra == 'gmpy'
|
37 |
+
Provides-Extra: tests
|
38 |
+
Requires-Dist: pytest (>=4.6) ; extra == 'tests'
|
39 |
+
|
40 |
+
mpmath
|
41 |
+
======
|
42 |
+
|
43 |
+
|pypi version| |Build status| |Code coverage status| |Zenodo Badge|
|
44 |
+
|
45 |
+
.. |pypi version| image:: https://img.shields.io/pypi/v/mpmath.svg
|
46 |
+
:target: https://pypi.python.org/pypi/mpmath
|
47 |
+
.. |Build status| image:: https://github.com/fredrik-johansson/mpmath/workflows/test/badge.svg
|
48 |
+
:target: https://github.com/fredrik-johansson/mpmath/actions?workflow=test
|
49 |
+
.. |Code coverage status| image:: https://codecov.io/gh/fredrik-johansson/mpmath/branch/master/graph/badge.svg
|
50 |
+
:target: https://codecov.io/gh/fredrik-johansson/mpmath
|
51 |
+
.. |Zenodo Badge| image:: https://zenodo.org/badge/2934512.svg
|
52 |
+
:target: https://zenodo.org/badge/latestdoi/2934512
|
53 |
+
|
54 |
+
A Python library for arbitrary-precision floating-point arithmetic.
|
55 |
+
|
56 |
+
Website: http://mpmath.org/
|
57 |
+
Main author: Fredrik Johansson <[email protected]>
|
58 |
+
|
59 |
+
Mpmath is free software released under the New BSD License (see the
|
60 |
+
LICENSE file for details)
|
61 |
+
|
62 |
+
0. History and credits
|
63 |
+
----------------------
|
64 |
+
|
65 |
+
The following people (among others) have contributed major patches
|
66 |
+
or new features to mpmath:
|
67 |
+
|
68 |
+
* Pearu Peterson <[email protected]>
|
69 |
+
* Mario Pernici <[email protected]>
|
70 |
+
* Ondrej Certik <[email protected]>
|
71 |
+
* Vinzent Steinberg <[email protected]>
|
72 |
+
* Nimish Telang <[email protected]>
|
73 |
+
* Mike Taschuk <[email protected]>
|
74 |
+
* Case Van Horsen <[email protected]>
|
75 |
+
* Jorn Baayen <[email protected]>
|
76 |
+
* Chris Smith <[email protected]>
|
77 |
+
* Juan Arias de Reyna <[email protected]>
|
78 |
+
* Ioannis Tziakos <[email protected]>
|
79 |
+
* Aaron Meurer <[email protected]>
|
80 |
+
* Stefan Krastanov <[email protected]>
|
81 |
+
* Ken Allen <[email protected]>
|
82 |
+
* Timo Hartmann <[email protected]>
|
83 |
+
* Sergey B Kirpichev <[email protected]>
|
84 |
+
* Kris Kuhlman <[email protected]>
|
85 |
+
* Paul Masson <[email protected]>
|
86 |
+
* Michael Kagalenko <[email protected]>
|
87 |
+
* Jonathan Warner <[email protected]>
|
88 |
+
* Max Gaukler <[email protected]>
|
89 |
+
* Guillermo Navas-Palencia <[email protected]>
|
90 |
+
* Nike Dattani <[email protected]>
|
91 |
+
|
92 |
+
Numerous other people have contributed by reporting bugs,
|
93 |
+
requesting new features, or suggesting improvements to the
|
94 |
+
documentation.
|
95 |
+
|
96 |
+
For a detailed changelog, including individual contributions,
|
97 |
+
see the CHANGES file.
|
98 |
+
|
99 |
+
Fredrik's work on mpmath during summer 2008 was sponsored by Google
|
100 |
+
as part of the Google Summer of Code program.
|
101 |
+
|
102 |
+
Fredrik's work on mpmath during summer 2009 was sponsored by the
|
103 |
+
American Institute of Mathematics under the support of the National Science
|
104 |
+
Foundation Grant No. 0757627 (FRG: L-functions and Modular Forms).
|
105 |
+
|
106 |
+
Any opinions, findings, and conclusions or recommendations expressed in this
|
107 |
+
material are those of the author(s) and do not necessarily reflect the
|
108 |
+
views of the sponsors.
|
109 |
+
|
110 |
+
Credit also goes to:
|
111 |
+
|
112 |
+
* The authors of the GMP library and the Python wrapper
|
113 |
+
gmpy, enabling mpmath to become much faster at
|
114 |
+
high precision
|
115 |
+
* The authors of MPFR, pari/gp, MPFUN, and other arbitrary-
|
116 |
+
precision libraries, whose documentation has been helpful
|
117 |
+
for implementing many of the algorithms in mpmath
|
118 |
+
* Wikipedia contributors; Abramowitz & Stegun; Gradshteyn & Ryzhik;
|
119 |
+
Wolfram Research for MathWorld and the Wolfram Functions site.
|
120 |
+
These are the main references used for special functions
|
121 |
+
implementations.
|
122 |
+
* George Brandl for developing the Sphinx documentation tool
|
123 |
+
used to build mpmath's documentation
|
124 |
+
|
125 |
+
Release history:
|
126 |
+
|
127 |
+
* Version 1.3.0 released on March 7, 2023
|
128 |
+
* Version 1.2.0 released on February 1, 2021
|
129 |
+
* Version 1.1.0 released on December 11, 2018
|
130 |
+
* Version 1.0.0 released on September 27, 2017
|
131 |
+
* Version 0.19 released on June 10, 2014
|
132 |
+
* Version 0.18 released on December 31, 2013
|
133 |
+
* Version 0.17 released on February 1, 2011
|
134 |
+
* Version 0.16 released on September 24, 2010
|
135 |
+
* Version 0.15 released on June 6, 2010
|
136 |
+
* Version 0.14 released on February 5, 2010
|
137 |
+
* Version 0.13 released on August 13, 2009
|
138 |
+
* Version 0.12 released on June 9, 2009
|
139 |
+
* Version 0.11 released on January 26, 2009
|
140 |
+
* Version 0.10 released on October 15, 2008
|
141 |
+
* Version 0.9 released on August 23, 2008
|
142 |
+
* Version 0.8 released on April 20, 2008
|
143 |
+
* Version 0.7 released on March 12, 2008
|
144 |
+
* Version 0.6 released on January 13, 2008
|
145 |
+
* Version 0.5 released on November 24, 2007
|
146 |
+
* Version 0.4 released on November 3, 2007
|
147 |
+
* Version 0.3 released on October 5, 2007
|
148 |
+
* Version 0.2 released on October 2, 2007
|
149 |
+
* Version 0.1 released on September 27, 2007
|
150 |
+
|
151 |
+
1. Download & installation
|
152 |
+
--------------------------
|
153 |
+
|
154 |
+
Mpmath requires Python 2.7 or 3.5 (or later versions). It has been tested
|
155 |
+
with CPython 2.7, 3.5 through 3.7 and for PyPy.
|
156 |
+
|
157 |
+
The latest release of mpmath can be downloaded from the mpmath
|
158 |
+
website and from https://github.com/fredrik-johansson/mpmath/releases
|
159 |
+
|
160 |
+
It should also be available in the Python Package Index at
|
161 |
+
https://pypi.python.org/pypi/mpmath
|
162 |
+
|
163 |
+
To install latest release of Mpmath with pip, simply run
|
164 |
+
|
165 |
+
``pip install mpmath``
|
166 |
+
|
167 |
+
Or unpack the mpmath archive and run
|
168 |
+
|
169 |
+
``python setup.py install``
|
170 |
+
|
171 |
+
Mpmath can also be installed using
|
172 |
+
|
173 |
+
``python -m easy_install mpmath``
|
174 |
+
|
175 |
+
The latest development code is available from
|
176 |
+
https://github.com/fredrik-johansson/mpmath
|
177 |
+
|
178 |
+
See the main documentation for more detailed instructions.
|
179 |
+
|
180 |
+
2. Running tests
|
181 |
+
----------------
|
182 |
+
|
183 |
+
The unit tests in mpmath/tests/ can be run via the script
|
184 |
+
runtests.py, but it is recommended to run them with py.test
|
185 |
+
(https://pytest.org/), especially
|
186 |
+
to generate more useful reports in case there are failures.
|
187 |
+
|
188 |
+
You may also want to check out the demo scripts in the demo
|
189 |
+
directory.
|
190 |
+
|
191 |
+
The master branch is automatically tested by Travis CI.
|
192 |
+
|
193 |
+
3. Documentation
|
194 |
+
----------------
|
195 |
+
|
196 |
+
Documentation in reStructuredText format is available in the
|
197 |
+
doc directory included with the source package. These files
|
198 |
+
are human-readable, but can be compiled to prettier HTML using
|
199 |
+
the build.py script (requires Sphinx, http://sphinx.pocoo.org/).
|
200 |
+
|
201 |
+
See setup.txt in the documentation for more information.
|
202 |
+
|
203 |
+
The most recent documentation is also available in HTML format:
|
204 |
+
|
205 |
+
http://mpmath.org/doc/current/
|
206 |
+
|
207 |
+
4. Known problems
|
208 |
+
-----------------
|
209 |
+
|
210 |
+
Mpmath is a work in progress. Major issues include:
|
211 |
+
|
212 |
+
* Some functions may return incorrect values when given extremely
|
213 |
+
large arguments or arguments very close to singularities.
|
214 |
+
|
215 |
+
* Directed rounding works for arithmetic operations. It is implemented
|
216 |
+
heuristically for other operations, and their results may be off by one
|
217 |
+
or two units in the last place (even if otherwise accurate).
|
218 |
+
|
219 |
+
* Some IEEE 754 features are not available. Inifinities and NaN are
|
220 |
+
partially supported; denormal rounding is currently not available
|
221 |
+
at all.
|
222 |
+
|
223 |
+
* The interface for switching precision and rounding is not finalized.
|
224 |
+
The current method is not threadsafe.
|
225 |
+
|
226 |
+
5. Help and bug reports
|
227 |
+
-----------------------
|
228 |
+
|
229 |
+
General questions and comments can be sent to the mpmath mailinglist,
|
230 | |
231 |
+
|
232 |
+
You can also report bugs and send patches to the mpmath issue tracker,
|
233 |
+
https://github.com/fredrik-johansson/mpmath/issues
|
env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/RECORD
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
mpmath-1.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
mpmath-1.3.0.dist-info/LICENSE,sha256=wmyugdpFCOXiSZhXd6M4IfGDIj67dNf4z7-Q_n7vL7c,1537
|
3 |
+
mpmath-1.3.0.dist-info/METADATA,sha256=RLZupES5wNGa6UgV01a_BHrmtoDBkmi1wmVofNaoFAY,8630
|
4 |
+
mpmath-1.3.0.dist-info/RECORD,,
|
5 |
+
mpmath-1.3.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
|
6 |
+
mpmath-1.3.0.dist-info/top_level.txt,sha256=BUVWrh8EVlkOhM1n3X9S8msTaVcC-3s6Sjt60avHYus,7
|
7 |
+
mpmath/__init__.py,sha256=skFYTSwfwDBLChAV6pI3SdewgAQR3UBtyrfIK_Jdn-g,8765
|
8 |
+
mpmath/__pycache__/__init__.cpython-310.pyc,,
|
9 |
+
mpmath/__pycache__/ctx_base.cpython-310.pyc,,
|
10 |
+
mpmath/__pycache__/ctx_fp.cpython-310.pyc,,
|
11 |
+
mpmath/__pycache__/ctx_iv.cpython-310.pyc,,
|
12 |
+
mpmath/__pycache__/ctx_mp.cpython-310.pyc,,
|
13 |
+
mpmath/__pycache__/ctx_mp_python.cpython-310.pyc,,
|
14 |
+
mpmath/__pycache__/function_docs.cpython-310.pyc,,
|
15 |
+
mpmath/__pycache__/identification.cpython-310.pyc,,
|
16 |
+
mpmath/__pycache__/math2.cpython-310.pyc,,
|
17 |
+
mpmath/__pycache__/rational.cpython-310.pyc,,
|
18 |
+
mpmath/__pycache__/usertools.cpython-310.pyc,,
|
19 |
+
mpmath/__pycache__/visualization.cpython-310.pyc,,
|
20 |
+
mpmath/calculus/__init__.py,sha256=UAgCIJ1YmaeyTqpNzjBlCZGeIzLtUZMEEpl99VWNjus,162
|
21 |
+
mpmath/calculus/__pycache__/__init__.cpython-310.pyc,,
|
22 |
+
mpmath/calculus/__pycache__/approximation.cpython-310.pyc,,
|
23 |
+
mpmath/calculus/__pycache__/calculus.cpython-310.pyc,,
|
24 |
+
mpmath/calculus/__pycache__/differentiation.cpython-310.pyc,,
|
25 |
+
mpmath/calculus/__pycache__/extrapolation.cpython-310.pyc,,
|
26 |
+
mpmath/calculus/__pycache__/inverselaplace.cpython-310.pyc,,
|
27 |
+
mpmath/calculus/__pycache__/odes.cpython-310.pyc,,
|
28 |
+
mpmath/calculus/__pycache__/optimization.cpython-310.pyc,,
|
29 |
+
mpmath/calculus/__pycache__/polynomials.cpython-310.pyc,,
|
30 |
+
mpmath/calculus/__pycache__/quadrature.cpython-310.pyc,,
|
31 |
+
mpmath/calculus/approximation.py,sha256=vyzu3YI6r63Oq1KFHrQz02mGXAcH23emqNYhJuUaFZ4,8817
|
32 |
+
mpmath/calculus/calculus.py,sha256=A0gSp0hxSyEDfugJViY3CeWalF-vK701YftzrjSQzQ4,112
|
33 |
+
mpmath/calculus/differentiation.py,sha256=2L6CBj8xtX9iip98NPbKsLtwtRjxi571wYmTMHFeL90,20226
|
34 |
+
mpmath/calculus/extrapolation.py,sha256=xM0rvk2DFEF4iR1Jhl-Y3aS93iW9VVJX7y9IGpmzC-A,73306
|
35 |
+
mpmath/calculus/inverselaplace.py,sha256=5-pn8N_t0PtgBTXixsXZ4xxrihK2J5gYsVfTKfDx4gA,36056
|
36 |
+
mpmath/calculus/odes.py,sha256=gaHiw7IJjsONNTAa6izFPZpmcg9uyTp8MULnGdzTIGo,9908
|
37 |
+
mpmath/calculus/optimization.py,sha256=bKnShXElBOmVOIOlFeksDsYCp9fYSmYwKmXDt0z26MM,32856
|
38 |
+
mpmath/calculus/polynomials.py,sha256=D16BhU_SHbVi06IxNwABHR-H77IylndNsN3muPTuFYs,7877
|
39 |
+
mpmath/calculus/quadrature.py,sha256=n-avtS8E43foV-5tr5lofgOBaiMUYE8AJjQcWI9QcKk,42432
|
40 |
+
mpmath/ctx_base.py,sha256=rfjmfMyA55x8R_cWFINUwWVTElfZmyx5erKDdauSEVw,15985
|
41 |
+
mpmath/ctx_fp.py,sha256=ctUjx_NoU0iFWk05cXDYCL2ZtLZOlWs1n6Zao3pbG2g,6572
|
42 |
+
mpmath/ctx_iv.py,sha256=tqdMr-GDfkZk1EhoGeCAajy7pQv-RWtrVqhYjfI8r4g,17211
|
43 |
+
mpmath/ctx_mp.py,sha256=d3r4t7xHNqSFtmqsA9Btq1Npy3WTM-pcM2_jeCyECxY,49452
|
44 |
+
mpmath/ctx_mp_python.py,sha256=3olYWo4lk1SnQ0A_IaZ181qqG8u5pxGat_v-L4Qtn3Y,37815
|
45 |
+
mpmath/function_docs.py,sha256=g4PP8n6ILXmHcLyA50sxK6Tmp_Z4_pRN-wDErU8D1i4,283512
|
46 |
+
mpmath/functions/__init__.py,sha256=YXVdhqv-6LKm6cr5xxtTNTtuD9zDPKGQl8GmS0xz2xo,330
|
47 |
+
mpmath/functions/__pycache__/__init__.cpython-310.pyc,,
|
48 |
+
mpmath/functions/__pycache__/bessel.cpython-310.pyc,,
|
49 |
+
mpmath/functions/__pycache__/elliptic.cpython-310.pyc,,
|
50 |
+
mpmath/functions/__pycache__/expintegrals.cpython-310.pyc,,
|
51 |
+
mpmath/functions/__pycache__/factorials.cpython-310.pyc,,
|
52 |
+
mpmath/functions/__pycache__/functions.cpython-310.pyc,,
|
53 |
+
mpmath/functions/__pycache__/hypergeometric.cpython-310.pyc,,
|
54 |
+
mpmath/functions/__pycache__/orthogonal.cpython-310.pyc,,
|
55 |
+
mpmath/functions/__pycache__/qfunctions.cpython-310.pyc,,
|
56 |
+
mpmath/functions/__pycache__/rszeta.cpython-310.pyc,,
|
57 |
+
mpmath/functions/__pycache__/signals.cpython-310.pyc,,
|
58 |
+
mpmath/functions/__pycache__/theta.cpython-310.pyc,,
|
59 |
+
mpmath/functions/__pycache__/zeta.cpython-310.pyc,,
|
60 |
+
mpmath/functions/__pycache__/zetazeros.cpython-310.pyc,,
|
61 |
+
mpmath/functions/bessel.py,sha256=dUPLu8frlK-vmf3-irX_7uvwyw4xccv6EIizmIZ88kM,37938
|
62 |
+
mpmath/functions/elliptic.py,sha256=qz0yVMb4lWEeOTDL_DWz5u5awmGIPKAsuZFJXgwHJNU,42237
|
63 |
+
mpmath/functions/expintegrals.py,sha256=75X_MRdYc1F_X73bgNiOJqwRlS2hqAzcFLl3RM2tCDc,11644
|
64 |
+
mpmath/functions/factorials.py,sha256=8_6kCR7e4k1GwxiAOJu0NRadeF4jA28qx4hidhu4ILk,5273
|
65 |
+
mpmath/functions/functions.py,sha256=ub2JExvqzCWLkm5yAm72Fr6fdWmZZUknq9_3w9MEigI,18100
|
66 |
+
mpmath/functions/hypergeometric.py,sha256=Z0OMAMC4ylK42n_SnamyFVnUx6zHLyCLCoJDSZ1JrHY,51570
|
67 |
+
mpmath/functions/orthogonal.py,sha256=FabkxKfBoSseA5flWu1a3re-2BYaew9augqIsT8LaLw,16097
|
68 |
+
mpmath/functions/qfunctions.py,sha256=a3EHGKQt_jMd4x9I772Jz-TGFnGY-arWqPvZGz9QSe0,7633
|
69 |
+
mpmath/functions/rszeta.py,sha256=yuUVp4ilIyDmXyE3WTBxDDjwfEJNypJnbPS-xPH5How,46184
|
70 |
+
mpmath/functions/signals.py,sha256=ELotwQaW1CDpv-eeJzOZ5c23NhfaZcj9_Gkb3psvS0Q,703
|
71 |
+
mpmath/functions/theta.py,sha256=KggOocczoMG6_HMoal4oEP7iZ4SKOou9JFE-WzY2r3M,37320
|
72 |
+
mpmath/functions/zeta.py,sha256=ue7JY7GXA0oX8q08sQJl2CSRrZ7kOt8HsftpVjnTwrE,36410
|
73 |
+
mpmath/functions/zetazeros.py,sha256=uq6TVyZBcY2MLX7VSdVfn0TOkowBLM9fXtnySEwaNzw,30858
|
74 |
+
mpmath/identification.py,sha256=7aMdngRAaeL_MafDUNbmEIlGQSklHDZ8pmPFt-OLgkw,29253
|
75 |
+
mpmath/libmp/__init__.py,sha256=UCDjLZw4brbklaCmSixCcPdLdHkz8sF_-6F_wr0duAg,3790
|
76 |
+
mpmath/libmp/__pycache__/__init__.cpython-310.pyc,,
|
77 |
+
mpmath/libmp/__pycache__/backend.cpython-310.pyc,,
|
78 |
+
mpmath/libmp/__pycache__/gammazeta.cpython-310.pyc,,
|
79 |
+
mpmath/libmp/__pycache__/libelefun.cpython-310.pyc,,
|
80 |
+
mpmath/libmp/__pycache__/libhyper.cpython-310.pyc,,
|
81 |
+
mpmath/libmp/__pycache__/libintmath.cpython-310.pyc,,
|
82 |
+
mpmath/libmp/__pycache__/libmpc.cpython-310.pyc,,
|
83 |
+
mpmath/libmp/__pycache__/libmpf.cpython-310.pyc,,
|
84 |
+
mpmath/libmp/__pycache__/libmpi.cpython-310.pyc,,
|
85 |
+
mpmath/libmp/backend.py,sha256=26A8pUkaGov26vrrFNQVyWJ5LDtK8sl3UHrYLecaTjA,3360
|
86 |
+
mpmath/libmp/gammazeta.py,sha256=Xqdw6PMoswDaSca_sOs-IglRuk3fb8c9p43M_lbcrlc,71469
|
87 |
+
mpmath/libmp/libelefun.py,sha256=joBZP4FOdxPfieWso1LPtSr6dHydpG_LQiF_bYQYWMg,43861
|
88 |
+
mpmath/libmp/libhyper.py,sha256=J9fmdDF6u27EcssEWvBuVaAa3hFjPvPN1SgRgu1dEbc,36624
|
89 |
+
mpmath/libmp/libintmath.py,sha256=aIRT0rkUZ_sdGQf3TNCLd-pBMvtQWjssbvFLfK7U0jc,16688
|
90 |
+
mpmath/libmp/libmpc.py,sha256=KBndUjs5YVS32-Id3fflDfYgpdW1Prx6zfo8Ez5Qbrs,26875
|
91 |
+
mpmath/libmp/libmpf.py,sha256=vpP0kNVkScbCVoZogJ4Watl4I7Ce0d4dzHVjfVe57so,45021
|
92 |
+
mpmath/libmp/libmpi.py,sha256=u0I5Eiwkqa-4-dXETi5k7MuaxBeZbvCAPFtl93U9YF0,27622
|
93 |
+
mpmath/math2.py,sha256=O5Dglg81SsW0wfHDUJcXOD8-cCaLvbVIvyw0sVmRbpI,18561
|
94 |
+
mpmath/matrices/__init__.py,sha256=ETzGDciYbq9ftiKwaMbJ15EI-KNXHrzRb-ZHehhqFjs,94
|
95 |
+
mpmath/matrices/__pycache__/__init__.cpython-310.pyc,,
|
96 |
+
mpmath/matrices/__pycache__/calculus.cpython-310.pyc,,
|
97 |
+
mpmath/matrices/__pycache__/eigen.cpython-310.pyc,,
|
98 |
+
mpmath/matrices/__pycache__/eigen_symmetric.cpython-310.pyc,,
|
99 |
+
mpmath/matrices/__pycache__/linalg.cpython-310.pyc,,
|
100 |
+
mpmath/matrices/__pycache__/matrices.cpython-310.pyc,,
|
101 |
+
mpmath/matrices/calculus.py,sha256=PNRq-p2nxgT-fzC54K2depi8ddhdx6Q86G8qpUiHeUY,18609
|
102 |
+
mpmath/matrices/eigen.py,sha256=GbDXI3CixzEdXxr1G86uUWkAngAvd-05MmSQ-Tsu_5k,24394
|
103 |
+
mpmath/matrices/eigen_symmetric.py,sha256=FPKPeQr1cGYw6Y6ea32a1YdEWQDLP6JlQHEA2WfNLYg,58534
|
104 |
+
mpmath/matrices/linalg.py,sha256=04C3ijzMFom7ob5fXBCDfyPPdo3BIboIeE8x2A6vqF0,26958
|
105 |
+
mpmath/matrices/matrices.py,sha256=o78Eq62EHQnxcsR0LBoWDEGREOoN4L2iDM1q3dQrw0o,32331
|
106 |
+
mpmath/rational.py,sha256=64d56fvZXngYZT7nOAHeFRUX77eJ1A0R3rpfWBU-mSo,5976
|
107 |
+
mpmath/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
108 |
+
mpmath/tests/__pycache__/__init__.cpython-310.pyc,,
|
109 |
+
mpmath/tests/__pycache__/extratest_gamma.cpython-310.pyc,,
|
110 |
+
mpmath/tests/__pycache__/extratest_zeta.cpython-310.pyc,,
|
111 |
+
mpmath/tests/__pycache__/runtests.cpython-310.pyc,,
|
112 |
+
mpmath/tests/__pycache__/test_basic_ops.cpython-310.pyc,,
|
113 |
+
mpmath/tests/__pycache__/test_bitwise.cpython-310.pyc,,
|
114 |
+
mpmath/tests/__pycache__/test_calculus.cpython-310.pyc,,
|
115 |
+
mpmath/tests/__pycache__/test_compatibility.cpython-310.pyc,,
|
116 |
+
mpmath/tests/__pycache__/test_convert.cpython-310.pyc,,
|
117 |
+
mpmath/tests/__pycache__/test_diff.cpython-310.pyc,,
|
118 |
+
mpmath/tests/__pycache__/test_division.cpython-310.pyc,,
|
119 |
+
mpmath/tests/__pycache__/test_eigen.cpython-310.pyc,,
|
120 |
+
mpmath/tests/__pycache__/test_eigen_symmetric.cpython-310.pyc,,
|
121 |
+
mpmath/tests/__pycache__/test_elliptic.cpython-310.pyc,,
|
122 |
+
mpmath/tests/__pycache__/test_fp.cpython-310.pyc,,
|
123 |
+
mpmath/tests/__pycache__/test_functions.cpython-310.pyc,,
|
124 |
+
mpmath/tests/__pycache__/test_functions2.cpython-310.pyc,,
|
125 |
+
mpmath/tests/__pycache__/test_gammazeta.cpython-310.pyc,,
|
126 |
+
mpmath/tests/__pycache__/test_hp.cpython-310.pyc,,
|
127 |
+
mpmath/tests/__pycache__/test_identify.cpython-310.pyc,,
|
128 |
+
mpmath/tests/__pycache__/test_interval.cpython-310.pyc,,
|
129 |
+
mpmath/tests/__pycache__/test_levin.cpython-310.pyc,,
|
130 |
+
mpmath/tests/__pycache__/test_linalg.cpython-310.pyc,,
|
131 |
+
mpmath/tests/__pycache__/test_matrices.cpython-310.pyc,,
|
132 |
+
mpmath/tests/__pycache__/test_mpmath.cpython-310.pyc,,
|
133 |
+
mpmath/tests/__pycache__/test_ode.cpython-310.pyc,,
|
134 |
+
mpmath/tests/__pycache__/test_pickle.cpython-310.pyc,,
|
135 |
+
mpmath/tests/__pycache__/test_power.cpython-310.pyc,,
|
136 |
+
mpmath/tests/__pycache__/test_quad.cpython-310.pyc,,
|
137 |
+
mpmath/tests/__pycache__/test_rootfinding.cpython-310.pyc,,
|
138 |
+
mpmath/tests/__pycache__/test_special.cpython-310.pyc,,
|
139 |
+
mpmath/tests/__pycache__/test_str.cpython-310.pyc,,
|
140 |
+
mpmath/tests/__pycache__/test_summation.cpython-310.pyc,,
|
141 |
+
mpmath/tests/__pycache__/test_trig.cpython-310.pyc,,
|
142 |
+
mpmath/tests/__pycache__/test_visualization.cpython-310.pyc,,
|
143 |
+
mpmath/tests/__pycache__/torture.cpython-310.pyc,,
|
144 |
+
mpmath/tests/extratest_gamma.py,sha256=xidhXUelILcxtiPGoTBHjqUOKIJzEaZ_v3nntGQyWZQ,7228
|
145 |
+
mpmath/tests/extratest_zeta.py,sha256=sg10j9RhjBpV2EdUqyYhGV2ERWvM--EvwwGIz6HTmlw,1003
|
146 |
+
mpmath/tests/runtests.py,sha256=7NUV82F3K_5AhU8mCLUFf5OibtT7uloFCwPyM3l71wM,5189
|
147 |
+
mpmath/tests/test_basic_ops.py,sha256=dsB8DRG-GrPzBaZ-bIauYabaeqXbfqBo9SIP9BqcTSs,15348
|
148 |
+
mpmath/tests/test_bitwise.py,sha256=-nLYhgQbhDza3SQM63BhktYntACagqMYx9ib3dPnTKM,7686
|
149 |
+
mpmath/tests/test_calculus.py,sha256=4oxtNfMpO4RLLoOzrv7r9-h8BcqfBsJIE6UpsHe7c4w,9187
|
150 |
+
mpmath/tests/test_compatibility.py,sha256=_t3ASZ3jhfAMnN1voWX7PDNIDzn-3PokkJGIdT1x7y0,2306
|
151 |
+
mpmath/tests/test_convert.py,sha256=JPcDcTJIWh5prIxjx5DM1aNWgqlUoF2KpHvAgK3uHi4,8834
|
152 |
+
mpmath/tests/test_diff.py,sha256=qjiF8NxQ8vueuZ5ZHGPQ-kjcj_I7Jh_fEdFtaA8DzEI,2466
|
153 |
+
mpmath/tests/test_division.py,sha256=6lUeZfmaBWvvszdqlWLMHgXPjVsxvW1WZpd4-jFWCpU,5340
|
154 |
+
mpmath/tests/test_eigen.py,sha256=2mnqVATGbsJkvSVHPpitfAk881twFfb3LsO3XikV9Hs,3905
|
155 |
+
mpmath/tests/test_eigen_symmetric.py,sha256=v0VimCicIU2owASDMBaP-t-30uq-pXcsglt95KBtNO4,8778
|
156 |
+
mpmath/tests/test_elliptic.py,sha256=Kjiwq9Bb6N_OOzzWewGQ1M_PMa7vRs42V0t90gloZxo,26225
|
157 |
+
mpmath/tests/test_fp.py,sha256=AJo0FTyH4BuUnUsv176LD956om308KGYndy-b54KGxM,89997
|
158 |
+
mpmath/tests/test_functions.py,sha256=b47VywdomoOX6KmMmz9-iv2IqVIydwKSuUw2pWlFHrY,30955
|
159 |
+
mpmath/tests/test_functions2.py,sha256=vlw2RWhL1oTcifnOMDx1a_YzN96UgNNIE5STeKRv1HY,96990
|
160 |
+
mpmath/tests/test_gammazeta.py,sha256=AB34O0DV7AlEf9Z4brnCadeQU5-uAwhWRw5FZas65DA,27917
|
161 |
+
mpmath/tests/test_hp.py,sha256=6hcENu6Te2klPEiTSeLBIRPlH7PADlJwFKbx8xpnOhg,10461
|
162 |
+
mpmath/tests/test_identify.py,sha256=lGUIPfrB2paTg0cFUo64GmMzF77F9gs9FQjX7gxGHV8,692
|
163 |
+
mpmath/tests/test_interval.py,sha256=TjYd7a9ca6iRJiLjw06isLeZTuGoGAPmgleDZ0cYfJ0,17527
|
164 |
+
mpmath/tests/test_levin.py,sha256=P8M11yV1dj_gdSNv5xuwCzFiF86QyRDtPMjURy6wJ28,5090
|
165 |
+
mpmath/tests/test_linalg.py,sha256=miKEnwB8iwWV13hi1bF1cg3hgB4rTKOR0fvDVfWmXds,10440
|
166 |
+
mpmath/tests/test_matrices.py,sha256=qyA4Ml2CvNvW034lzB01G6wVgNr7UrgZqh2wkMXtpzM,7944
|
167 |
+
mpmath/tests/test_mpmath.py,sha256=LVyJUeofiaxW-zLKWVBCz59L9UQsjlW0Ts9_oBiEv_4,196
|
168 |
+
mpmath/tests/test_ode.py,sha256=zAxexBH4fnmFNO4bvEHbug1NJWC5zqfFaVDlYijowkY,1822
|
169 |
+
mpmath/tests/test_pickle.py,sha256=Y8CKmDLFsJHUqG8CDaBw5ilrPP4YT1xijVduLpQ7XFE,401
|
170 |
+
mpmath/tests/test_power.py,sha256=sz_K02SmNxpa6Kb1uJLN_N4tXTJGdQ___vPRshEN7Gk,5227
|
171 |
+
mpmath/tests/test_quad.py,sha256=49Ltft0vZ_kdKLL5s-Kj-BzAVoF5LPVEUeNUzdOkghI,3893
|
172 |
+
mpmath/tests/test_rootfinding.py,sha256=umQegEaKHmYOEl5jEyoD-VLKDtXsTJJkepKEr4c0dC0,3132
|
173 |
+
mpmath/tests/test_special.py,sha256=YbMIoMIkJEvvKYIzS0CXthJFG0--j6un7-tcE6b7FPM,2848
|
174 |
+
mpmath/tests/test_str.py,sha256=0WsGD9hMPRi8zcuYMA9Cu2mOvQiCFskPwMsMf8lBDK4,544
|
175 |
+
mpmath/tests/test_summation.py,sha256=fdNlsvRVOsbWxbhlyDLDaEO2S8kTJrRMKIvB5-aNci0,2035
|
176 |
+
mpmath/tests/test_trig.py,sha256=zPtkIEnZaThxcWur4k7BX8-2Jmj-AhO191Svv7ANYUU,4799
|
177 |
+
mpmath/tests/test_visualization.py,sha256=1PqtkoUx-WsKYgTRiu5o9pBc85kwhf1lzU2eobDQCJM,944
|
178 |
+
mpmath/tests/torture.py,sha256=LD95oES7JY2KroELK-m-jhvtbvZaKChnt0Cq7kFMNCw,7868
|
179 |
+
mpmath/usertools.py,sha256=a-TDw7XSRsPdBEffxOooDV4WDFfuXnO58P75dcAD87I,3029
|
180 |
+
mpmath/visualization.py,sha256=pnnbjcd9AhFVRBZavYX5gjx4ytK_kXoDDisYR6EpXhs,10627
|
env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.38.4)
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
5 |
+
|
env-llmeval/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
mpmath
|
env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (604 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-310.pyc
ADDED
Binary file (3.97 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-310.pyc
ADDED
Binary file (3.43 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-310.pyc
ADDED
Binary file (4.62 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-310.pyc
ADDED
Binary file (3.82 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/take.cpython-310.pyc
ADDED
Binary file (13.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-310.pyc
ADDED
Binary file (1.01 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/core/tools/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/pandas/core/tools/timedeltas.py
ADDED
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
from typing import (
|
7 |
+
TYPE_CHECKING,
|
8 |
+
overload,
|
9 |
+
)
|
10 |
+
import warnings
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
|
14 |
+
from pandas._libs import lib
|
15 |
+
from pandas._libs.tslibs import (
|
16 |
+
NaT,
|
17 |
+
NaTType,
|
18 |
+
)
|
19 |
+
from pandas._libs.tslibs.timedeltas import (
|
20 |
+
Timedelta,
|
21 |
+
disallow_ambiguous_unit,
|
22 |
+
parse_timedelta_unit,
|
23 |
+
)
|
24 |
+
from pandas.util._exceptions import find_stack_level
|
25 |
+
|
26 |
+
from pandas.core.dtypes.common import is_list_like
|
27 |
+
from pandas.core.dtypes.dtypes import ArrowDtype
|
28 |
+
from pandas.core.dtypes.generic import (
|
29 |
+
ABCIndex,
|
30 |
+
ABCSeries,
|
31 |
+
)
|
32 |
+
|
33 |
+
from pandas.core.arrays.timedeltas import sequence_to_td64ns
|
34 |
+
|
35 |
+
if TYPE_CHECKING:
|
36 |
+
from collections.abc import Hashable
|
37 |
+
from datetime import timedelta
|
38 |
+
|
39 |
+
from pandas._libs.tslibs.timedeltas import UnitChoices
|
40 |
+
from pandas._typing import (
|
41 |
+
ArrayLike,
|
42 |
+
DateTimeErrorChoices,
|
43 |
+
)
|
44 |
+
|
45 |
+
from pandas import (
|
46 |
+
Index,
|
47 |
+
Series,
|
48 |
+
TimedeltaIndex,
|
49 |
+
)
|
50 |
+
|
51 |
+
|
52 |
+
@overload
|
53 |
+
def to_timedelta(
|
54 |
+
arg: str | float | timedelta,
|
55 |
+
unit: UnitChoices | None = ...,
|
56 |
+
errors: DateTimeErrorChoices = ...,
|
57 |
+
) -> Timedelta:
|
58 |
+
...
|
59 |
+
|
60 |
+
|
61 |
+
@overload
|
62 |
+
def to_timedelta(
|
63 |
+
arg: Series,
|
64 |
+
unit: UnitChoices | None = ...,
|
65 |
+
errors: DateTimeErrorChoices = ...,
|
66 |
+
) -> Series:
|
67 |
+
...
|
68 |
+
|
69 |
+
|
70 |
+
@overload
|
71 |
+
def to_timedelta(
|
72 |
+
arg: list | tuple | range | ArrayLike | Index,
|
73 |
+
unit: UnitChoices | None = ...,
|
74 |
+
errors: DateTimeErrorChoices = ...,
|
75 |
+
) -> TimedeltaIndex:
|
76 |
+
...
|
77 |
+
|
78 |
+
|
79 |
+
def to_timedelta(
|
80 |
+
arg: str
|
81 |
+
| int
|
82 |
+
| float
|
83 |
+
| timedelta
|
84 |
+
| list
|
85 |
+
| tuple
|
86 |
+
| range
|
87 |
+
| ArrayLike
|
88 |
+
| Index
|
89 |
+
| Series,
|
90 |
+
unit: UnitChoices | None = None,
|
91 |
+
errors: DateTimeErrorChoices = "raise",
|
92 |
+
) -> Timedelta | TimedeltaIndex | Series:
|
93 |
+
"""
|
94 |
+
Convert argument to timedelta.
|
95 |
+
|
96 |
+
Timedeltas are absolute differences in times, expressed in difference
|
97 |
+
units (e.g. days, hours, minutes, seconds). This method converts
|
98 |
+
an argument from a recognized timedelta format / value into
|
99 |
+
a Timedelta type.
|
100 |
+
|
101 |
+
Parameters
|
102 |
+
----------
|
103 |
+
arg : str, timedelta, list-like or Series
|
104 |
+
The data to be converted to timedelta.
|
105 |
+
|
106 |
+
.. versionchanged:: 2.0
|
107 |
+
Strings with units 'M', 'Y' and 'y' do not represent
|
108 |
+
unambiguous timedelta values and will raise an exception.
|
109 |
+
|
110 |
+
unit : str, optional
|
111 |
+
Denotes the unit of the arg for numeric `arg`. Defaults to ``"ns"``.
|
112 |
+
|
113 |
+
Possible values:
|
114 |
+
|
115 |
+
* 'W'
|
116 |
+
* 'D' / 'days' / 'day'
|
117 |
+
* 'hours' / 'hour' / 'hr' / 'h' / 'H'
|
118 |
+
* 'm' / 'minute' / 'min' / 'minutes' / 'T'
|
119 |
+
* 's' / 'seconds' / 'sec' / 'second' / 'S'
|
120 |
+
* 'ms' / 'milliseconds' / 'millisecond' / 'milli' / 'millis' / 'L'
|
121 |
+
* 'us' / 'microseconds' / 'microsecond' / 'micro' / 'micros' / 'U'
|
122 |
+
* 'ns' / 'nanoseconds' / 'nano' / 'nanos' / 'nanosecond' / 'N'
|
123 |
+
|
124 |
+
Must not be specified when `arg` contains strings and ``errors="raise"``.
|
125 |
+
|
126 |
+
.. deprecated:: 2.2.0
|
127 |
+
Units 'H', 'T', 'S', 'L', 'U' and 'N' are deprecated and will be removed
|
128 |
+
in a future version. Please use 'h', 'min', 's', 'ms', 'us', and 'ns'
|
129 |
+
instead of 'H', 'T', 'S', 'L', 'U' and 'N'.
|
130 |
+
|
131 |
+
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
|
132 |
+
- If 'raise', then invalid parsing will raise an exception.
|
133 |
+
- If 'coerce', then invalid parsing will be set as NaT.
|
134 |
+
- If 'ignore', then invalid parsing will return the input.
|
135 |
+
|
136 |
+
Returns
|
137 |
+
-------
|
138 |
+
timedelta
|
139 |
+
If parsing succeeded.
|
140 |
+
Return type depends on input:
|
141 |
+
|
142 |
+
- list-like: TimedeltaIndex of timedelta64 dtype
|
143 |
+
- Series: Series of timedelta64 dtype
|
144 |
+
- scalar: Timedelta
|
145 |
+
|
146 |
+
See Also
|
147 |
+
--------
|
148 |
+
DataFrame.astype : Cast argument to a specified dtype.
|
149 |
+
to_datetime : Convert argument to datetime.
|
150 |
+
convert_dtypes : Convert dtypes.
|
151 |
+
|
152 |
+
Notes
|
153 |
+
-----
|
154 |
+
If the precision is higher than nanoseconds, the precision of the duration is
|
155 |
+
truncated to nanoseconds for string inputs.
|
156 |
+
|
157 |
+
Examples
|
158 |
+
--------
|
159 |
+
Parsing a single string to a Timedelta:
|
160 |
+
|
161 |
+
>>> pd.to_timedelta('1 days 06:05:01.00003')
|
162 |
+
Timedelta('1 days 06:05:01.000030')
|
163 |
+
>>> pd.to_timedelta('15.5us')
|
164 |
+
Timedelta('0 days 00:00:00.000015500')
|
165 |
+
|
166 |
+
Parsing a list or array of strings:
|
167 |
+
|
168 |
+
>>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
|
169 |
+
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT],
|
170 |
+
dtype='timedelta64[ns]', freq=None)
|
171 |
+
|
172 |
+
Converting numbers by specifying the `unit` keyword argument:
|
173 |
+
|
174 |
+
>>> pd.to_timedelta(np.arange(5), unit='s')
|
175 |
+
TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02',
|
176 |
+
'0 days 00:00:03', '0 days 00:00:04'],
|
177 |
+
dtype='timedelta64[ns]', freq=None)
|
178 |
+
>>> pd.to_timedelta(np.arange(5), unit='d')
|
179 |
+
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
|
180 |
+
dtype='timedelta64[ns]', freq=None)
|
181 |
+
"""
|
182 |
+
if unit is not None:
|
183 |
+
unit = parse_timedelta_unit(unit)
|
184 |
+
disallow_ambiguous_unit(unit)
|
185 |
+
|
186 |
+
if errors not in ("ignore", "raise", "coerce"):
|
187 |
+
raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'.")
|
188 |
+
if errors == "ignore":
|
189 |
+
# GH#54467
|
190 |
+
warnings.warn(
|
191 |
+
"errors='ignore' is deprecated and will raise in a future version. "
|
192 |
+
"Use to_timedelta without passing `errors` and catch exceptions "
|
193 |
+
"explicitly instead",
|
194 |
+
FutureWarning,
|
195 |
+
stacklevel=find_stack_level(),
|
196 |
+
)
|
197 |
+
|
198 |
+
if arg is None:
|
199 |
+
return arg
|
200 |
+
elif isinstance(arg, ABCSeries):
|
201 |
+
values = _convert_listlike(arg._values, unit=unit, errors=errors)
|
202 |
+
return arg._constructor(values, index=arg.index, name=arg.name)
|
203 |
+
elif isinstance(arg, ABCIndex):
|
204 |
+
return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
|
205 |
+
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
|
206 |
+
# extract array scalar and process below
|
207 |
+
# error: Incompatible types in assignment (expression has type "object",
|
208 |
+
# variable has type "Union[str, int, float, timedelta, List[Any],
|
209 |
+
# Tuple[Any, ...], Union[Union[ExtensionArray, ndarray[Any, Any]], Index,
|
210 |
+
# Series]]") [assignment]
|
211 |
+
arg = lib.item_from_zerodim(arg) # type: ignore[assignment]
|
212 |
+
elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
|
213 |
+
return _convert_listlike(arg, unit=unit, errors=errors)
|
214 |
+
elif getattr(arg, "ndim", 1) > 1:
|
215 |
+
raise TypeError(
|
216 |
+
"arg must be a string, timedelta, list, tuple, 1-d array, or Series"
|
217 |
+
)
|
218 |
+
|
219 |
+
if isinstance(arg, str) and unit is not None:
|
220 |
+
raise ValueError("unit must not be specified if the input is/contains a str")
|
221 |
+
|
222 |
+
# ...so it must be a scalar value. Return scalar.
|
223 |
+
return _coerce_scalar_to_timedelta_type(arg, unit=unit, errors=errors)
|
224 |
+
|
225 |
+
|
226 |
+
def _coerce_scalar_to_timedelta_type(
|
227 |
+
r, unit: UnitChoices | None = "ns", errors: DateTimeErrorChoices = "raise"
|
228 |
+
):
|
229 |
+
"""Convert string 'r' to a timedelta object."""
|
230 |
+
result: Timedelta | NaTType
|
231 |
+
|
232 |
+
try:
|
233 |
+
result = Timedelta(r, unit)
|
234 |
+
except ValueError:
|
235 |
+
if errors == "raise":
|
236 |
+
raise
|
237 |
+
if errors == "ignore":
|
238 |
+
return r
|
239 |
+
|
240 |
+
# coerce
|
241 |
+
result = NaT
|
242 |
+
|
243 |
+
return result
|
244 |
+
|
245 |
+
|
246 |
+
def _convert_listlike(
|
247 |
+
arg,
|
248 |
+
unit: UnitChoices | None = None,
|
249 |
+
errors: DateTimeErrorChoices = "raise",
|
250 |
+
name: Hashable | None = None,
|
251 |
+
):
|
252 |
+
"""Convert a list of objects to a timedelta index object."""
|
253 |
+
arg_dtype = getattr(arg, "dtype", None)
|
254 |
+
if isinstance(arg, (list, tuple)) or arg_dtype is None:
|
255 |
+
# This is needed only to ensure that in the case where we end up
|
256 |
+
# returning arg (errors == "ignore"), and where the input is a
|
257 |
+
# generator, we return a useful list-like instead of a
|
258 |
+
# used-up generator
|
259 |
+
if not hasattr(arg, "__array__"):
|
260 |
+
arg = list(arg)
|
261 |
+
arg = np.array(arg, dtype=object)
|
262 |
+
elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.kind == "m":
|
263 |
+
return arg
|
264 |
+
|
265 |
+
try:
|
266 |
+
td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]
|
267 |
+
except ValueError:
|
268 |
+
if errors == "ignore":
|
269 |
+
return arg
|
270 |
+
else:
|
271 |
+
# This else-block accounts for the cases when errors='raise'
|
272 |
+
# and errors='coerce'. If errors == 'raise', these errors
|
273 |
+
# should be raised. If errors == 'coerce', we shouldn't
|
274 |
+
# expect any errors to be raised, since all parsing errors
|
275 |
+
# cause coercion to pd.NaT. However, if an error / bug is
|
276 |
+
# introduced that causes an Exception to be raised, we would
|
277 |
+
# like to surface it.
|
278 |
+
raise
|
279 |
+
|
280 |
+
from pandas import TimedeltaIndex
|
281 |
+
|
282 |
+
value = TimedeltaIndex(td64arr, name=name)
|
283 |
+
return value
|
env-llmeval/lib/python3.10/site-packages/pandas/core/tools/times.py
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from datetime import (
|
4 |
+
datetime,
|
5 |
+
time,
|
6 |
+
)
|
7 |
+
from typing import TYPE_CHECKING
|
8 |
+
import warnings
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
from pandas._libs.lib import is_list_like
|
13 |
+
from pandas.util._exceptions import find_stack_level
|
14 |
+
|
15 |
+
from pandas.core.dtypes.generic import (
|
16 |
+
ABCIndex,
|
17 |
+
ABCSeries,
|
18 |
+
)
|
19 |
+
from pandas.core.dtypes.missing import notna
|
20 |
+
|
21 |
+
if TYPE_CHECKING:
|
22 |
+
from pandas._typing import DateTimeErrorChoices
|
23 |
+
|
24 |
+
|
25 |
+
def to_time(
|
26 |
+
arg,
|
27 |
+
format: str | None = None,
|
28 |
+
infer_time_format: bool = False,
|
29 |
+
errors: DateTimeErrorChoices = "raise",
|
30 |
+
):
|
31 |
+
"""
|
32 |
+
Parse time strings to time objects using fixed strptime formats ("%H:%M",
|
33 |
+
"%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p",
|
34 |
+
"%I%M%S%p")
|
35 |
+
|
36 |
+
Use infer_time_format if all the strings are in the same format to speed
|
37 |
+
up conversion.
|
38 |
+
|
39 |
+
Parameters
|
40 |
+
----------
|
41 |
+
arg : string in time format, datetime.time, list, tuple, 1-d array, Series
|
42 |
+
format : str, default None
|
43 |
+
Format used to convert arg into a time object. If None, fixed formats
|
44 |
+
are used.
|
45 |
+
infer_time_format: bool, default False
|
46 |
+
Infer the time format based on the first non-NaN element. If all
|
47 |
+
strings are in the same format, this will speed up conversion.
|
48 |
+
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
|
49 |
+
- If 'raise', then invalid parsing will raise an exception
|
50 |
+
- If 'coerce', then invalid parsing will be set as None
|
51 |
+
- If 'ignore', then invalid parsing will return the input
|
52 |
+
|
53 |
+
Returns
|
54 |
+
-------
|
55 |
+
datetime.time
|
56 |
+
"""
|
57 |
+
if errors == "ignore":
|
58 |
+
# GH#54467
|
59 |
+
warnings.warn(
|
60 |
+
"errors='ignore' is deprecated and will raise in a future version. "
|
61 |
+
"Use to_time without passing `errors` and catch exceptions "
|
62 |
+
"explicitly instead",
|
63 |
+
FutureWarning,
|
64 |
+
stacklevel=find_stack_level(),
|
65 |
+
)
|
66 |
+
|
67 |
+
def _convert_listlike(arg, format):
|
68 |
+
if isinstance(arg, (list, tuple)):
|
69 |
+
arg = np.array(arg, dtype="O")
|
70 |
+
|
71 |
+
elif getattr(arg, "ndim", 1) > 1:
|
72 |
+
raise TypeError(
|
73 |
+
"arg must be a string, datetime, list, tuple, 1-d array, or Series"
|
74 |
+
)
|
75 |
+
|
76 |
+
arg = np.asarray(arg, dtype="O")
|
77 |
+
|
78 |
+
if infer_time_format and format is None:
|
79 |
+
format = _guess_time_format_for_array(arg)
|
80 |
+
|
81 |
+
times: list[time | None] = []
|
82 |
+
if format is not None:
|
83 |
+
for element in arg:
|
84 |
+
try:
|
85 |
+
times.append(datetime.strptime(element, format).time())
|
86 |
+
except (ValueError, TypeError) as err:
|
87 |
+
if errors == "raise":
|
88 |
+
msg = (
|
89 |
+
f"Cannot convert {element} to a time with given "
|
90 |
+
f"format {format}"
|
91 |
+
)
|
92 |
+
raise ValueError(msg) from err
|
93 |
+
if errors == "ignore":
|
94 |
+
return arg
|
95 |
+
else:
|
96 |
+
times.append(None)
|
97 |
+
else:
|
98 |
+
formats = _time_formats[:]
|
99 |
+
format_found = False
|
100 |
+
for element in arg:
|
101 |
+
time_object = None
|
102 |
+
try:
|
103 |
+
time_object = time.fromisoformat(element)
|
104 |
+
except (ValueError, TypeError):
|
105 |
+
for time_format in formats:
|
106 |
+
try:
|
107 |
+
time_object = datetime.strptime(element, time_format).time()
|
108 |
+
if not format_found:
|
109 |
+
# Put the found format in front
|
110 |
+
fmt = formats.pop(formats.index(time_format))
|
111 |
+
formats.insert(0, fmt)
|
112 |
+
format_found = True
|
113 |
+
break
|
114 |
+
except (ValueError, TypeError):
|
115 |
+
continue
|
116 |
+
|
117 |
+
if time_object is not None:
|
118 |
+
times.append(time_object)
|
119 |
+
elif errors == "raise":
|
120 |
+
raise ValueError(f"Cannot convert arg {arg} to a time")
|
121 |
+
elif errors == "ignore":
|
122 |
+
return arg
|
123 |
+
else:
|
124 |
+
times.append(None)
|
125 |
+
|
126 |
+
return times
|
127 |
+
|
128 |
+
if arg is None:
|
129 |
+
return arg
|
130 |
+
elif isinstance(arg, time):
|
131 |
+
return arg
|
132 |
+
elif isinstance(arg, ABCSeries):
|
133 |
+
values = _convert_listlike(arg._values, format)
|
134 |
+
return arg._constructor(values, index=arg.index, name=arg.name)
|
135 |
+
elif isinstance(arg, ABCIndex):
|
136 |
+
return _convert_listlike(arg, format)
|
137 |
+
elif is_list_like(arg):
|
138 |
+
return _convert_listlike(arg, format)
|
139 |
+
|
140 |
+
return _convert_listlike(np.array([arg]), format)[0]
|
141 |
+
|
142 |
+
|
143 |
+
# Fixed time formats for time parsing
|
144 |
+
_time_formats = [
|
145 |
+
"%H:%M",
|
146 |
+
"%H%M",
|
147 |
+
"%I:%M%p",
|
148 |
+
"%I%M%p",
|
149 |
+
"%H:%M:%S",
|
150 |
+
"%H%M%S",
|
151 |
+
"%I:%M:%S%p",
|
152 |
+
"%I%M%S%p",
|
153 |
+
]
|
154 |
+
|
155 |
+
|
156 |
+
def _guess_time_format_for_array(arr):
|
157 |
+
# Try to guess the format based on the first non-NaN element
|
158 |
+
non_nan_elements = notna(arr).nonzero()[0]
|
159 |
+
if len(non_nan_elements):
|
160 |
+
element = arr[non_nan_elements[0]]
|
161 |
+
for time_format in _time_formats:
|
162 |
+
try:
|
163 |
+
datetime.strptime(element, time_format)
|
164 |
+
return time_format
|
165 |
+
except ValueError:
|
166 |
+
pass
|
167 |
+
|
168 |
+
return None
|
env-llmeval/lib/python3.10/site-packages/psutil/__init__.py
ADDED
@@ -0,0 +1,2492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
# -*- coding: utf-8 -*-
|
2 |
+
|
3 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
4 |
+
# Use of this source code is governed by a BSD-style license that can be
|
5 |
+
# found in the LICENSE file.
|
6 |
+
|
7 |
+
"""psutil is a cross-platform library for retrieving information on
|
8 |
+
running processes and system utilization (CPU, memory, disks, network,
|
9 |
+
sensors) in Python. Supported platforms:
|
10 |
+
|
11 |
+
- Linux
|
12 |
+
- Windows
|
13 |
+
- macOS
|
14 |
+
- FreeBSD
|
15 |
+
- OpenBSD
|
16 |
+
- NetBSD
|
17 |
+
- Sun Solaris
|
18 |
+
- AIX
|
19 |
+
|
20 |
+
Works with Python versions 2.7 and 3.6+.
|
21 |
+
"""
|
22 |
+
|
23 |
+
from __future__ import division
|
24 |
+
|
25 |
+
import collections
|
26 |
+
import contextlib
|
27 |
+
import datetime
|
28 |
+
import functools
|
29 |
+
import os
|
30 |
+
import signal
|
31 |
+
import subprocess
|
32 |
+
import sys
|
33 |
+
import threading
|
34 |
+
import time
|
35 |
+
|
36 |
+
|
37 |
+
try:
|
38 |
+
import pwd
|
39 |
+
except ImportError:
|
40 |
+
pwd = None
|
41 |
+
|
42 |
+
from . import _common
|
43 |
+
from ._common import AIX
|
44 |
+
from ._common import BSD
|
45 |
+
from ._common import CONN_CLOSE
|
46 |
+
from ._common import CONN_CLOSE_WAIT
|
47 |
+
from ._common import CONN_CLOSING
|
48 |
+
from ._common import CONN_ESTABLISHED
|
49 |
+
from ._common import CONN_FIN_WAIT1
|
50 |
+
from ._common import CONN_FIN_WAIT2
|
51 |
+
from ._common import CONN_LAST_ACK
|
52 |
+
from ._common import CONN_LISTEN
|
53 |
+
from ._common import CONN_NONE
|
54 |
+
from ._common import CONN_SYN_RECV
|
55 |
+
from ._common import CONN_SYN_SENT
|
56 |
+
from ._common import CONN_TIME_WAIT
|
57 |
+
from ._common import FREEBSD # NOQA
|
58 |
+
from ._common import LINUX
|
59 |
+
from ._common import MACOS
|
60 |
+
from ._common import NETBSD # NOQA
|
61 |
+
from ._common import NIC_DUPLEX_FULL
|
62 |
+
from ._common import NIC_DUPLEX_HALF
|
63 |
+
from ._common import NIC_DUPLEX_UNKNOWN
|
64 |
+
from ._common import OPENBSD # NOQA
|
65 |
+
from ._common import OSX # deprecated alias
|
66 |
+
from ._common import POSIX # NOQA
|
67 |
+
from ._common import POWER_TIME_UNKNOWN
|
68 |
+
from ._common import POWER_TIME_UNLIMITED
|
69 |
+
from ._common import STATUS_DEAD
|
70 |
+
from ._common import STATUS_DISK_SLEEP
|
71 |
+
from ._common import STATUS_IDLE
|
72 |
+
from ._common import STATUS_LOCKED
|
73 |
+
from ._common import STATUS_PARKED
|
74 |
+
from ._common import STATUS_RUNNING
|
75 |
+
from ._common import STATUS_SLEEPING
|
76 |
+
from ._common import STATUS_STOPPED
|
77 |
+
from ._common import STATUS_TRACING_STOP
|
78 |
+
from ._common import STATUS_WAITING
|
79 |
+
from ._common import STATUS_WAKING
|
80 |
+
from ._common import STATUS_ZOMBIE
|
81 |
+
from ._common import SUNOS
|
82 |
+
from ._common import WINDOWS
|
83 |
+
from ._common import AccessDenied
|
84 |
+
from ._common import Error
|
85 |
+
from ._common import NoSuchProcess
|
86 |
+
from ._common import TimeoutExpired
|
87 |
+
from ._common import ZombieProcess
|
88 |
+
from ._common import memoize_when_activated
|
89 |
+
from ._common import wrap_numbers as _wrap_numbers
|
90 |
+
from ._compat import PY3 as _PY3
|
91 |
+
from ._compat import PermissionError
|
92 |
+
from ._compat import ProcessLookupError
|
93 |
+
from ._compat import SubprocessTimeoutExpired as _SubprocessTimeoutExpired
|
94 |
+
from ._compat import long
|
95 |
+
|
96 |
+
|
97 |
+
if LINUX:
|
98 |
+
# This is public API and it will be retrieved from _pslinux.py
|
99 |
+
# via sys.modules.
|
100 |
+
PROCFS_PATH = "/proc"
|
101 |
+
|
102 |
+
from . import _pslinux as _psplatform
|
103 |
+
from ._pslinux import IOPRIO_CLASS_BE # NOQA
|
104 |
+
from ._pslinux import IOPRIO_CLASS_IDLE # NOQA
|
105 |
+
from ._pslinux import IOPRIO_CLASS_NONE # NOQA
|
106 |
+
from ._pslinux import IOPRIO_CLASS_RT # NOQA
|
107 |
+
|
108 |
+
elif WINDOWS:
|
109 |
+
from . import _pswindows as _psplatform
|
110 |
+
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA
|
111 |
+
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA
|
112 |
+
from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA
|
113 |
+
from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA
|
114 |
+
from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA
|
115 |
+
from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA
|
116 |
+
from ._pswindows import CONN_DELETE_TCB # NOQA
|
117 |
+
from ._pswindows import IOPRIO_HIGH # NOQA
|
118 |
+
from ._pswindows import IOPRIO_LOW # NOQA
|
119 |
+
from ._pswindows import IOPRIO_NORMAL # NOQA
|
120 |
+
from ._pswindows import IOPRIO_VERYLOW # NOQA
|
121 |
+
|
122 |
+
elif MACOS:
|
123 |
+
from . import _psosx as _psplatform
|
124 |
+
|
125 |
+
elif BSD:
|
126 |
+
from . import _psbsd as _psplatform
|
127 |
+
|
128 |
+
elif SUNOS:
|
129 |
+
from . import _pssunos as _psplatform
|
130 |
+
from ._pssunos import CONN_BOUND # NOQA
|
131 |
+
from ._pssunos import CONN_IDLE # NOQA
|
132 |
+
|
133 |
+
# This is public writable API which is read from _pslinux.py and
|
134 |
+
# _pssunos.py via sys.modules.
|
135 |
+
PROCFS_PATH = "/proc"
|
136 |
+
|
137 |
+
elif AIX:
|
138 |
+
from . import _psaix as _psplatform
|
139 |
+
|
140 |
+
# This is public API and it will be retrieved from _pslinux.py
|
141 |
+
# via sys.modules.
|
142 |
+
PROCFS_PATH = "/proc"
|
143 |
+
|
144 |
+
else: # pragma: no cover
|
145 |
+
raise NotImplementedError('platform %s is not supported' % sys.platform)
|
146 |
+
|
147 |
+
|
148 |
+
# fmt: off
|
149 |
+
__all__ = [
|
150 |
+
# exceptions
|
151 |
+
"Error", "NoSuchProcess", "ZombieProcess", "AccessDenied",
|
152 |
+
"TimeoutExpired",
|
153 |
+
|
154 |
+
# constants
|
155 |
+
"version_info", "__version__",
|
156 |
+
|
157 |
+
"STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
|
158 |
+
"STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
|
159 |
+
"STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED",
|
160 |
+
"STATUS_PARKED",
|
161 |
+
|
162 |
+
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
|
163 |
+
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
|
164 |
+
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
|
165 |
+
# "CONN_IDLE", "CONN_BOUND",
|
166 |
+
|
167 |
+
"AF_LINK",
|
168 |
+
|
169 |
+
"NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN",
|
170 |
+
|
171 |
+
"POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED",
|
172 |
+
|
173 |
+
"BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX",
|
174 |
+
"SUNOS", "WINDOWS", "AIX",
|
175 |
+
|
176 |
+
# "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA",
|
177 |
+
# "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE",
|
178 |
+
# "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE",
|
179 |
+
# "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING",
|
180 |
+
|
181 |
+
# classes
|
182 |
+
"Process", "Popen",
|
183 |
+
|
184 |
+
# functions
|
185 |
+
"pid_exists", "pids", "process_iter", "wait_procs", # proc
|
186 |
+
"virtual_memory", "swap_memory", # memory
|
187 |
+
"cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu
|
188 |
+
"cpu_stats", # "cpu_freq", "getloadavg"
|
189 |
+
"net_io_counters", "net_connections", "net_if_addrs", # network
|
190 |
+
"net_if_stats",
|
191 |
+
"disk_io_counters", "disk_partitions", "disk_usage", # disk
|
192 |
+
# "sensors_temperatures", "sensors_battery", "sensors_fans" # sensors
|
193 |
+
"users", "boot_time", # others
|
194 |
+
]
|
195 |
+
# fmt: on
|
196 |
+
|
197 |
+
|
198 |
+
__all__.extend(_psplatform.__extra__all__)
|
199 |
+
|
200 |
+
# Linux, FreeBSD
|
201 |
+
if hasattr(_psplatform.Process, "rlimit"):
|
202 |
+
# Populate global namespace with RLIM* constants.
|
203 |
+
from . import _psutil_posix
|
204 |
+
|
205 |
+
_globals = globals()
|
206 |
+
_name = None
|
207 |
+
for _name in dir(_psutil_posix):
|
208 |
+
if _name.startswith('RLIM') and _name.isupper():
|
209 |
+
_globals[_name] = getattr(_psutil_posix, _name)
|
210 |
+
__all__.append(_name)
|
211 |
+
del _globals, _name
|
212 |
+
|
213 |
+
AF_LINK = _psplatform.AF_LINK
|
214 |
+
|
215 |
+
__author__ = "Giampaolo Rodola'"
|
216 |
+
__version__ = "5.9.8"
|
217 |
+
version_info = tuple([int(num) for num in __version__.split('.')])
|
218 |
+
|
219 |
+
_timer = getattr(time, 'monotonic', time.time)
|
220 |
+
_TOTAL_PHYMEM = None
|
221 |
+
_LOWEST_PID = None
|
222 |
+
_SENTINEL = object()
|
223 |
+
|
224 |
+
# Sanity check in case the user messed up with psutil installation
|
225 |
+
# or did something weird with sys.path. In this case we might end
|
226 |
+
# up importing a python module using a C extension module which
|
227 |
+
# was compiled for a different version of psutil.
|
228 |
+
# We want to prevent that by failing sooner rather than later.
|
229 |
+
# See: https://github.com/giampaolo/psutil/issues/564
|
230 |
+
if int(__version__.replace('.', '')) != getattr(
|
231 |
+
_psplatform.cext, 'version', None
|
232 |
+
):
|
233 |
+
msg = "version conflict: %r C extension " % _psplatform.cext.__file__
|
234 |
+
msg += "module was built for another version of psutil"
|
235 |
+
if hasattr(_psplatform.cext, 'version'):
|
236 |
+
msg += " (%s instead of %s)" % (
|
237 |
+
'.'.join([x for x in str(_psplatform.cext.version)]),
|
238 |
+
__version__,
|
239 |
+
)
|
240 |
+
else:
|
241 |
+
msg += " (different than %s)" % __version__
|
242 |
+
msg += "; you may try to 'pip uninstall psutil', manually remove %s" % (
|
243 |
+
getattr(
|
244 |
+
_psplatform.cext,
|
245 |
+
"__file__",
|
246 |
+
"the existing psutil install directory",
|
247 |
+
)
|
248 |
+
)
|
249 |
+
msg += " or clean the virtual env somehow, then reinstall"
|
250 |
+
raise ImportError(msg)
|
251 |
+
|
252 |
+
|
253 |
+
# =====================================================================
|
254 |
+
# --- Utils
|
255 |
+
# =====================================================================
|
256 |
+
|
257 |
+
|
258 |
+
if hasattr(_psplatform, 'ppid_map'):
|
259 |
+
# Faster version (Windows and Linux).
|
260 |
+
_ppid_map = _psplatform.ppid_map
|
261 |
+
else: # pragma: no cover
|
262 |
+
|
263 |
+
def _ppid_map():
|
264 |
+
"""Return a {pid: ppid, ...} dict for all running processes in
|
265 |
+
one shot. Used to speed up Process.children().
|
266 |
+
"""
|
267 |
+
ret = {}
|
268 |
+
for pid in pids():
|
269 |
+
try:
|
270 |
+
ret[pid] = _psplatform.Process(pid).ppid()
|
271 |
+
except (NoSuchProcess, ZombieProcess):
|
272 |
+
pass
|
273 |
+
return ret
|
274 |
+
|
275 |
+
|
276 |
+
def _pprint_secs(secs):
|
277 |
+
"""Format seconds in a human readable form."""
|
278 |
+
now = time.time()
|
279 |
+
secs_ago = int(now - secs)
|
280 |
+
fmt = "%H:%M:%S" if secs_ago < 60 * 60 * 24 else "%Y-%m-%d %H:%M:%S"
|
281 |
+
return datetime.datetime.fromtimestamp(secs).strftime(fmt)
|
282 |
+
|
283 |
+
|
284 |
+
# =====================================================================
|
285 |
+
# --- Process class
|
286 |
+
# =====================================================================
|
287 |
+
|
288 |
+
|
289 |
+
class Process(object): # noqa: UP004
|
290 |
+
"""Represents an OS process with the given PID.
|
291 |
+
If PID is omitted current process PID (os.getpid()) is used.
|
292 |
+
Raise NoSuchProcess if PID does not exist.
|
293 |
+
|
294 |
+
Note that most of the methods of this class do not make sure
|
295 |
+
the PID of the process being queried has been reused over time.
|
296 |
+
That means you might end up retrieving an information referring
|
297 |
+
to another process in case the original one this instance
|
298 |
+
refers to is gone in the meantime.
|
299 |
+
|
300 |
+
The only exceptions for which process identity is pre-emptively
|
301 |
+
checked and guaranteed are:
|
302 |
+
|
303 |
+
- parent()
|
304 |
+
- children()
|
305 |
+
- nice() (set)
|
306 |
+
- ionice() (set)
|
307 |
+
- rlimit() (set)
|
308 |
+
- cpu_affinity (set)
|
309 |
+
- suspend()
|
310 |
+
- resume()
|
311 |
+
- send_signal()
|
312 |
+
- terminate()
|
313 |
+
- kill()
|
314 |
+
|
315 |
+
To prevent this problem for all other methods you can:
|
316 |
+
- use is_running() before querying the process
|
317 |
+
- if you're continuously iterating over a set of Process
|
318 |
+
instances use process_iter() which pre-emptively checks
|
319 |
+
process identity for every yielded instance
|
320 |
+
"""
|
321 |
+
|
322 |
+
def __init__(self, pid=None):
|
323 |
+
self._init(pid)
|
324 |
+
|
325 |
+
def _init(self, pid, _ignore_nsp=False):
|
326 |
+
if pid is None:
|
327 |
+
pid = os.getpid()
|
328 |
+
else:
|
329 |
+
if not _PY3 and not isinstance(pid, (int, long)):
|
330 |
+
msg = "pid must be an integer (got %r)" % pid
|
331 |
+
raise TypeError(msg)
|
332 |
+
if pid < 0:
|
333 |
+
msg = "pid must be a positive integer (got %s)" % pid
|
334 |
+
raise ValueError(msg)
|
335 |
+
try:
|
336 |
+
_psplatform.cext.check_pid_range(pid)
|
337 |
+
except OverflowError:
|
338 |
+
msg = "process PID out of range (got %s)" % pid
|
339 |
+
raise NoSuchProcess(pid, msg=msg)
|
340 |
+
|
341 |
+
self._pid = pid
|
342 |
+
self._name = None
|
343 |
+
self._exe = None
|
344 |
+
self._create_time = None
|
345 |
+
self._gone = False
|
346 |
+
self._pid_reused = False
|
347 |
+
self._hash = None
|
348 |
+
self._lock = threading.RLock()
|
349 |
+
# used for caching on Windows only (on POSIX ppid may change)
|
350 |
+
self._ppid = None
|
351 |
+
# platform-specific modules define an _psplatform.Process
|
352 |
+
# implementation class
|
353 |
+
self._proc = _psplatform.Process(pid)
|
354 |
+
self._last_sys_cpu_times = None
|
355 |
+
self._last_proc_cpu_times = None
|
356 |
+
self._exitcode = _SENTINEL
|
357 |
+
# cache creation time for later use in is_running() method
|
358 |
+
try:
|
359 |
+
self.create_time()
|
360 |
+
except AccessDenied:
|
361 |
+
# We should never get here as AFAIK we're able to get
|
362 |
+
# process creation time on all platforms even as a
|
363 |
+
# limited user.
|
364 |
+
pass
|
365 |
+
except ZombieProcess:
|
366 |
+
# Zombies can still be queried by this class (although
|
367 |
+
# not always) and pids() return them so just go on.
|
368 |
+
pass
|
369 |
+
except NoSuchProcess:
|
370 |
+
if not _ignore_nsp:
|
371 |
+
msg = "process PID not found"
|
372 |
+
raise NoSuchProcess(pid, msg=msg)
|
373 |
+
else:
|
374 |
+
self._gone = True
|
375 |
+
# This pair is supposed to identify a Process instance
|
376 |
+
# univocally over time (the PID alone is not enough as
|
377 |
+
# it might refer to a process whose PID has been reused).
|
378 |
+
# This will be used later in __eq__() and is_running().
|
379 |
+
self._ident = (self.pid, self._create_time)
|
380 |
+
|
381 |
+
def __str__(self):
|
382 |
+
info = collections.OrderedDict()
|
383 |
+
info["pid"] = self.pid
|
384 |
+
if self._name:
|
385 |
+
info['name'] = self._name
|
386 |
+
with self.oneshot():
|
387 |
+
try:
|
388 |
+
info["name"] = self.name()
|
389 |
+
info["status"] = self.status()
|
390 |
+
except ZombieProcess:
|
391 |
+
info["status"] = "zombie"
|
392 |
+
except NoSuchProcess:
|
393 |
+
info["status"] = "terminated"
|
394 |
+
except AccessDenied:
|
395 |
+
pass
|
396 |
+
if self._exitcode not in (_SENTINEL, None):
|
397 |
+
info["exitcode"] = self._exitcode
|
398 |
+
if self._create_time is not None:
|
399 |
+
info['started'] = _pprint_secs(self._create_time)
|
400 |
+
return "%s.%s(%s)" % (
|
401 |
+
self.__class__.__module__,
|
402 |
+
self.__class__.__name__,
|
403 |
+
", ".join(["%s=%r" % (k, v) for k, v in info.items()]),
|
404 |
+
)
|
405 |
+
|
406 |
+
__repr__ = __str__
|
407 |
+
|
408 |
+
def __eq__(self, other):
|
409 |
+
# Test for equality with another Process object based
|
410 |
+
# on PID and creation time.
|
411 |
+
if not isinstance(other, Process):
|
412 |
+
return NotImplemented
|
413 |
+
if OPENBSD or NETBSD: # pragma: no cover
|
414 |
+
# Zombie processes on Open/NetBSD have a creation time of
|
415 |
+
# 0.0. This covers the case when a process started normally
|
416 |
+
# (so it has a ctime), then it turned into a zombie. It's
|
417 |
+
# important to do this because is_running() depends on
|
418 |
+
# __eq__.
|
419 |
+
pid1, ctime1 = self._ident
|
420 |
+
pid2, ctime2 = other._ident
|
421 |
+
if pid1 == pid2:
|
422 |
+
if ctime1 and not ctime2:
|
423 |
+
try:
|
424 |
+
return self.status() == STATUS_ZOMBIE
|
425 |
+
except Error:
|
426 |
+
pass
|
427 |
+
return self._ident == other._ident
|
428 |
+
|
429 |
+
def __ne__(self, other):
|
430 |
+
return not self == other
|
431 |
+
|
432 |
+
def __hash__(self):
|
433 |
+
if self._hash is None:
|
434 |
+
self._hash = hash(self._ident)
|
435 |
+
return self._hash
|
436 |
+
|
437 |
+
def _raise_if_pid_reused(self):
|
438 |
+
"""Raises NoSuchProcess in case process PID has been reused."""
|
439 |
+
if not self.is_running() and self._pid_reused:
|
440 |
+
# We may directly raise NSP in here already if PID is just
|
441 |
+
# not running, but I prefer NSP to be raised naturally by
|
442 |
+
# the actual Process API call. This way unit tests will tell
|
443 |
+
# us if the API is broken (aka don't raise NSP when it
|
444 |
+
# should). We also remain consistent with all other "get"
|
445 |
+
# APIs which don't use _raise_if_pid_reused().
|
446 |
+
msg = "process no longer exists and its PID has been reused"
|
447 |
+
raise NoSuchProcess(self.pid, self._name, msg=msg)
|
448 |
+
|
449 |
+
@property
|
450 |
+
def pid(self):
|
451 |
+
"""The process PID."""
|
452 |
+
return self._pid
|
453 |
+
|
454 |
+
# --- utility methods
|
455 |
+
|
456 |
+
@contextlib.contextmanager
|
457 |
+
def oneshot(self):
|
458 |
+
"""Utility context manager which considerably speeds up the
|
459 |
+
retrieval of multiple process information at the same time.
|
460 |
+
|
461 |
+
Internally different process info (e.g. name, ppid, uids,
|
462 |
+
gids, ...) may be fetched by using the same routine, but
|
463 |
+
only one information is returned and the others are discarded.
|
464 |
+
When using this context manager the internal routine is
|
465 |
+
executed once (in the example below on name()) and the
|
466 |
+
other info are cached.
|
467 |
+
|
468 |
+
The cache is cleared when exiting the context manager block.
|
469 |
+
The advice is to use this every time you retrieve more than
|
470 |
+
one information about the process. If you're lucky, you'll
|
471 |
+
get a hell of a speedup.
|
472 |
+
|
473 |
+
>>> import psutil
|
474 |
+
>>> p = psutil.Process()
|
475 |
+
>>> with p.oneshot():
|
476 |
+
... p.name() # collect multiple info
|
477 |
+
... p.cpu_times() # return cached value
|
478 |
+
... p.cpu_percent() # return cached value
|
479 |
+
... p.create_time() # return cached value
|
480 |
+
...
|
481 |
+
>>>
|
482 |
+
"""
|
483 |
+
with self._lock:
|
484 |
+
if hasattr(self, "_cache"):
|
485 |
+
# NOOP: this covers the use case where the user enters the
|
486 |
+
# context twice:
|
487 |
+
#
|
488 |
+
# >>> with p.oneshot():
|
489 |
+
# ... with p.oneshot():
|
490 |
+
# ...
|
491 |
+
#
|
492 |
+
# Also, since as_dict() internally uses oneshot()
|
493 |
+
# I expect that the code below will be a pretty common
|
494 |
+
# "mistake" that the user will make, so let's guard
|
495 |
+
# against that:
|
496 |
+
#
|
497 |
+
# >>> with p.oneshot():
|
498 |
+
# ... p.as_dict()
|
499 |
+
# ...
|
500 |
+
yield
|
501 |
+
else:
|
502 |
+
try:
|
503 |
+
# cached in case cpu_percent() is used
|
504 |
+
self.cpu_times.cache_activate(self)
|
505 |
+
# cached in case memory_percent() is used
|
506 |
+
self.memory_info.cache_activate(self)
|
507 |
+
# cached in case parent() is used
|
508 |
+
self.ppid.cache_activate(self)
|
509 |
+
# cached in case username() is used
|
510 |
+
if POSIX:
|
511 |
+
self.uids.cache_activate(self)
|
512 |
+
# specific implementation cache
|
513 |
+
self._proc.oneshot_enter()
|
514 |
+
yield
|
515 |
+
finally:
|
516 |
+
self.cpu_times.cache_deactivate(self)
|
517 |
+
self.memory_info.cache_deactivate(self)
|
518 |
+
self.ppid.cache_deactivate(self)
|
519 |
+
if POSIX:
|
520 |
+
self.uids.cache_deactivate(self)
|
521 |
+
self._proc.oneshot_exit()
|
522 |
+
|
523 |
+
def as_dict(self, attrs=None, ad_value=None):
|
524 |
+
"""Utility method returning process information as a
|
525 |
+
hashable dictionary.
|
526 |
+
If *attrs* is specified it must be a list of strings
|
527 |
+
reflecting available Process class' attribute names
|
528 |
+
(e.g. ['cpu_times', 'name']) else all public (read
|
529 |
+
only) attributes are assumed.
|
530 |
+
*ad_value* is the value which gets assigned in case
|
531 |
+
AccessDenied or ZombieProcess exception is raised when
|
532 |
+
retrieving that particular process information.
|
533 |
+
"""
|
534 |
+
valid_names = _as_dict_attrnames
|
535 |
+
if attrs is not None:
|
536 |
+
if not isinstance(attrs, (list, tuple, set, frozenset)):
|
537 |
+
msg = "invalid attrs type %s" % type(attrs)
|
538 |
+
raise TypeError(msg)
|
539 |
+
attrs = set(attrs)
|
540 |
+
invalid_names = attrs - valid_names
|
541 |
+
if invalid_names:
|
542 |
+
msg = "invalid attr name%s %s" % (
|
543 |
+
"s" if len(invalid_names) > 1 else "",
|
544 |
+
", ".join(map(repr, invalid_names)),
|
545 |
+
)
|
546 |
+
raise ValueError(msg)
|
547 |
+
|
548 |
+
retdict = {}
|
549 |
+
ls = attrs or valid_names
|
550 |
+
with self.oneshot():
|
551 |
+
for name in ls:
|
552 |
+
try:
|
553 |
+
if name == 'pid':
|
554 |
+
ret = self.pid
|
555 |
+
else:
|
556 |
+
meth = getattr(self, name)
|
557 |
+
ret = meth()
|
558 |
+
except (AccessDenied, ZombieProcess):
|
559 |
+
ret = ad_value
|
560 |
+
except NotImplementedError:
|
561 |
+
# in case of not implemented functionality (may happen
|
562 |
+
# on old or exotic systems) we want to crash only if
|
563 |
+
# the user explicitly asked for that particular attr
|
564 |
+
if attrs:
|
565 |
+
raise
|
566 |
+
continue
|
567 |
+
retdict[name] = ret
|
568 |
+
return retdict
|
569 |
+
|
570 |
+
def parent(self):
|
571 |
+
"""Return the parent process as a Process object pre-emptively
|
572 |
+
checking whether PID has been reused.
|
573 |
+
If no parent is known return None.
|
574 |
+
"""
|
575 |
+
lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0]
|
576 |
+
if self.pid == lowest_pid:
|
577 |
+
return None
|
578 |
+
ppid = self.ppid()
|
579 |
+
if ppid is not None:
|
580 |
+
ctime = self.create_time()
|
581 |
+
try:
|
582 |
+
parent = Process(ppid)
|
583 |
+
if parent.create_time() <= ctime:
|
584 |
+
return parent
|
585 |
+
# ...else ppid has been reused by another process
|
586 |
+
except NoSuchProcess:
|
587 |
+
pass
|
588 |
+
|
589 |
+
def parents(self):
|
590 |
+
"""Return the parents of this process as a list of Process
|
591 |
+
instances. If no parents are known return an empty list.
|
592 |
+
"""
|
593 |
+
parents = []
|
594 |
+
proc = self.parent()
|
595 |
+
while proc is not None:
|
596 |
+
parents.append(proc)
|
597 |
+
proc = proc.parent()
|
598 |
+
return parents
|
599 |
+
|
600 |
+
def is_running(self):
|
601 |
+
"""Return whether this process is running.
|
602 |
+
It also checks if PID has been reused by another process in
|
603 |
+
which case return False.
|
604 |
+
"""
|
605 |
+
if self._gone or self._pid_reused:
|
606 |
+
return False
|
607 |
+
try:
|
608 |
+
# Checking if PID is alive is not enough as the PID might
|
609 |
+
# have been reused by another process: we also want to
|
610 |
+
# verify process identity.
|
611 |
+
# Process identity / uniqueness over time is guaranteed by
|
612 |
+
# (PID + creation time) and that is verified in __eq__.
|
613 |
+
self._pid_reused = self != Process(self.pid)
|
614 |
+
return not self._pid_reused
|
615 |
+
except ZombieProcess:
|
616 |
+
# We should never get here as it's already handled in
|
617 |
+
# Process.__init__; here just for extra safety.
|
618 |
+
return True
|
619 |
+
except NoSuchProcess:
|
620 |
+
self._gone = True
|
621 |
+
return False
|
622 |
+
|
623 |
+
# --- actual API
|
624 |
+
|
625 |
+
@memoize_when_activated
|
626 |
+
def ppid(self):
|
627 |
+
"""The process parent PID.
|
628 |
+
On Windows the return value is cached after first call.
|
629 |
+
"""
|
630 |
+
# On POSIX we don't want to cache the ppid as it may unexpectedly
|
631 |
+
# change to 1 (init) in case this process turns into a zombie:
|
632 |
+
# https://github.com/giampaolo/psutil/issues/321
|
633 |
+
# http://stackoverflow.com/questions/356722/
|
634 |
+
|
635 |
+
# XXX should we check creation time here rather than in
|
636 |
+
# Process.parent()?
|
637 |
+
self._raise_if_pid_reused()
|
638 |
+
if POSIX:
|
639 |
+
return self._proc.ppid()
|
640 |
+
else: # pragma: no cover
|
641 |
+
self._ppid = self._ppid or self._proc.ppid()
|
642 |
+
return self._ppid
|
643 |
+
|
644 |
+
def name(self):
|
645 |
+
"""The process name. The return value is cached after first call."""
|
646 |
+
# Process name is only cached on Windows as on POSIX it may
|
647 |
+
# change, see:
|
648 |
+
# https://github.com/giampaolo/psutil/issues/692
|
649 |
+
if WINDOWS and self._name is not None:
|
650 |
+
return self._name
|
651 |
+
name = self._proc.name()
|
652 |
+
if POSIX and len(name) >= 15:
|
653 |
+
# On UNIX the name gets truncated to the first 15 characters.
|
654 |
+
# If it matches the first part of the cmdline we return that
|
655 |
+
# one instead because it's usually more explicative.
|
656 |
+
# Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
|
657 |
+
try:
|
658 |
+
cmdline = self.cmdline()
|
659 |
+
except (AccessDenied, ZombieProcess):
|
660 |
+
# Just pass and return the truncated name: it's better
|
661 |
+
# than nothing. Note: there are actual cases where a
|
662 |
+
# zombie process can return a name() but not a
|
663 |
+
# cmdline(), see:
|
664 |
+
# https://github.com/giampaolo/psutil/issues/2239
|
665 |
+
pass
|
666 |
+
else:
|
667 |
+
if cmdline:
|
668 |
+
extended_name = os.path.basename(cmdline[0])
|
669 |
+
if extended_name.startswith(name):
|
670 |
+
name = extended_name
|
671 |
+
self._name = name
|
672 |
+
self._proc._name = name
|
673 |
+
return name
|
674 |
+
|
675 |
+
def exe(self):
|
676 |
+
"""The process executable as an absolute path.
|
677 |
+
May also be an empty string.
|
678 |
+
The return value is cached after first call.
|
679 |
+
"""
|
680 |
+
|
681 |
+
def guess_it(fallback):
|
682 |
+
# try to guess exe from cmdline[0] in absence of a native
|
683 |
+
# exe representation
|
684 |
+
cmdline = self.cmdline()
|
685 |
+
if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
|
686 |
+
exe = cmdline[0] # the possible exe
|
687 |
+
# Attempt to guess only in case of an absolute path.
|
688 |
+
# It is not safe otherwise as the process might have
|
689 |
+
# changed cwd.
|
690 |
+
if (
|
691 |
+
os.path.isabs(exe)
|
692 |
+
and os.path.isfile(exe)
|
693 |
+
and os.access(exe, os.X_OK)
|
694 |
+
):
|
695 |
+
return exe
|
696 |
+
if isinstance(fallback, AccessDenied):
|
697 |
+
raise fallback
|
698 |
+
return fallback
|
699 |
+
|
700 |
+
if self._exe is None:
|
701 |
+
try:
|
702 |
+
exe = self._proc.exe()
|
703 |
+
except AccessDenied as err:
|
704 |
+
return guess_it(fallback=err)
|
705 |
+
else:
|
706 |
+
if not exe:
|
707 |
+
# underlying implementation can legitimately return an
|
708 |
+
# empty string; if that's the case we don't want to
|
709 |
+
# raise AD while guessing from the cmdline
|
710 |
+
try:
|
711 |
+
exe = guess_it(fallback=exe)
|
712 |
+
except AccessDenied:
|
713 |
+
pass
|
714 |
+
self._exe = exe
|
715 |
+
return self._exe
|
716 |
+
|
717 |
+
def cmdline(self):
|
718 |
+
"""The command line this process has been called with."""
|
719 |
+
return self._proc.cmdline()
|
720 |
+
|
721 |
+
def status(self):
|
722 |
+
"""The process current status as a STATUS_* constant."""
|
723 |
+
try:
|
724 |
+
return self._proc.status()
|
725 |
+
except ZombieProcess:
|
726 |
+
return STATUS_ZOMBIE
|
727 |
+
|
728 |
+
def username(self):
|
729 |
+
"""The name of the user that owns the process.
|
730 |
+
On UNIX this is calculated by using *real* process uid.
|
731 |
+
"""
|
732 |
+
if POSIX:
|
733 |
+
if pwd is None:
|
734 |
+
# might happen if python was installed from sources
|
735 |
+
msg = "requires pwd module shipped with standard python"
|
736 |
+
raise ImportError(msg)
|
737 |
+
real_uid = self.uids().real
|
738 |
+
try:
|
739 |
+
return pwd.getpwuid(real_uid).pw_name
|
740 |
+
except KeyError:
|
741 |
+
# the uid can't be resolved by the system
|
742 |
+
return str(real_uid)
|
743 |
+
else:
|
744 |
+
return self._proc.username()
|
745 |
+
|
746 |
+
def create_time(self):
|
747 |
+
"""The process creation time as a floating point number
|
748 |
+
expressed in seconds since the epoch.
|
749 |
+
The return value is cached after first call.
|
750 |
+
"""
|
751 |
+
if self._create_time is None:
|
752 |
+
self._create_time = self._proc.create_time()
|
753 |
+
return self._create_time
|
754 |
+
|
755 |
+
def cwd(self):
|
756 |
+
"""Process current working directory as an absolute path."""
|
757 |
+
return self._proc.cwd()
|
758 |
+
|
759 |
+
def nice(self, value=None):
|
760 |
+
"""Get or set process niceness (priority)."""
|
761 |
+
if value is None:
|
762 |
+
return self._proc.nice_get()
|
763 |
+
else:
|
764 |
+
self._raise_if_pid_reused()
|
765 |
+
self._proc.nice_set(value)
|
766 |
+
|
767 |
+
if POSIX:
|
768 |
+
|
769 |
+
@memoize_when_activated
|
770 |
+
def uids(self):
|
771 |
+
"""Return process UIDs as a (real, effective, saved)
|
772 |
+
namedtuple.
|
773 |
+
"""
|
774 |
+
return self._proc.uids()
|
775 |
+
|
776 |
+
def gids(self):
|
777 |
+
"""Return process GIDs as a (real, effective, saved)
|
778 |
+
namedtuple.
|
779 |
+
"""
|
780 |
+
return self._proc.gids()
|
781 |
+
|
782 |
+
def terminal(self):
|
783 |
+
"""The terminal associated with this process, if any,
|
784 |
+
else None.
|
785 |
+
"""
|
786 |
+
return self._proc.terminal()
|
787 |
+
|
788 |
+
def num_fds(self):
|
789 |
+
"""Return the number of file descriptors opened by this
|
790 |
+
process (POSIX only).
|
791 |
+
"""
|
792 |
+
return self._proc.num_fds()
|
793 |
+
|
794 |
+
# Linux, BSD, AIX and Windows only
|
795 |
+
if hasattr(_psplatform.Process, "io_counters"):
|
796 |
+
|
797 |
+
def io_counters(self):
|
798 |
+
"""Return process I/O statistics as a
|
799 |
+
(read_count, write_count, read_bytes, write_bytes)
|
800 |
+
namedtuple.
|
801 |
+
Those are the number of read/write calls performed and the
|
802 |
+
amount of bytes read and written by the process.
|
803 |
+
"""
|
804 |
+
return self._proc.io_counters()
|
805 |
+
|
806 |
+
# Linux and Windows
|
807 |
+
if hasattr(_psplatform.Process, "ionice_get"):
|
808 |
+
|
809 |
+
def ionice(self, ioclass=None, value=None):
|
810 |
+
"""Get or set process I/O niceness (priority).
|
811 |
+
|
812 |
+
On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
|
813 |
+
*value* is a number which goes from 0 to 7. The higher the
|
814 |
+
value, the lower the I/O priority of the process.
|
815 |
+
|
816 |
+
On Windows only *ioclass* is used and it can be set to 2
|
817 |
+
(normal), 1 (low) or 0 (very low).
|
818 |
+
|
819 |
+
Available on Linux and Windows > Vista only.
|
820 |
+
"""
|
821 |
+
if ioclass is None:
|
822 |
+
if value is not None:
|
823 |
+
msg = "'ioclass' argument must be specified"
|
824 |
+
raise ValueError(msg)
|
825 |
+
return self._proc.ionice_get()
|
826 |
+
else:
|
827 |
+
self._raise_if_pid_reused()
|
828 |
+
return self._proc.ionice_set(ioclass, value)
|
829 |
+
|
830 |
+
# Linux / FreeBSD only
|
831 |
+
if hasattr(_psplatform.Process, "rlimit"):
|
832 |
+
|
833 |
+
def rlimit(self, resource, limits=None):
|
834 |
+
"""Get or set process resource limits as a (soft, hard)
|
835 |
+
tuple.
|
836 |
+
|
837 |
+
*resource* is one of the RLIMIT_* constants.
|
838 |
+
*limits* is supposed to be a (soft, hard) tuple.
|
839 |
+
|
840 |
+
See "man prlimit" for further info.
|
841 |
+
Available on Linux and FreeBSD only.
|
842 |
+
"""
|
843 |
+
if limits is not None:
|
844 |
+
self._raise_if_pid_reused()
|
845 |
+
return self._proc.rlimit(resource, limits)
|
846 |
+
|
847 |
+
# Windows, Linux and FreeBSD only
|
848 |
+
if hasattr(_psplatform.Process, "cpu_affinity_get"):
|
849 |
+
|
850 |
+
def cpu_affinity(self, cpus=None):
|
851 |
+
"""Get or set process CPU affinity.
|
852 |
+
If specified, *cpus* must be a list of CPUs for which you
|
853 |
+
want to set the affinity (e.g. [0, 1]).
|
854 |
+
If an empty list is passed, all egible CPUs are assumed
|
855 |
+
(and set).
|
856 |
+
(Windows, Linux and BSD only).
|
857 |
+
"""
|
858 |
+
if cpus is None:
|
859 |
+
return sorted(set(self._proc.cpu_affinity_get()))
|
860 |
+
else:
|
861 |
+
self._raise_if_pid_reused()
|
862 |
+
if not cpus:
|
863 |
+
if hasattr(self._proc, "_get_eligible_cpus"):
|
864 |
+
cpus = self._proc._get_eligible_cpus()
|
865 |
+
else:
|
866 |
+
cpus = tuple(range(len(cpu_times(percpu=True))))
|
867 |
+
self._proc.cpu_affinity_set(list(set(cpus)))
|
868 |
+
|
869 |
+
# Linux, FreeBSD, SunOS
|
870 |
+
if hasattr(_psplatform.Process, "cpu_num"):
|
871 |
+
|
872 |
+
def cpu_num(self):
|
873 |
+
"""Return what CPU this process is currently running on.
|
874 |
+
The returned number should be <= psutil.cpu_count()
|
875 |
+
and <= len(psutil.cpu_percent(percpu=True)).
|
876 |
+
It may be used in conjunction with
|
877 |
+
psutil.cpu_percent(percpu=True) to observe the system
|
878 |
+
workload distributed across CPUs.
|
879 |
+
"""
|
880 |
+
return self._proc.cpu_num()
|
881 |
+
|
882 |
+
# All platforms has it, but maybe not in the future.
|
883 |
+
if hasattr(_psplatform.Process, "environ"):
|
884 |
+
|
885 |
+
def environ(self):
|
886 |
+
"""The environment variables of the process as a dict. Note: this
|
887 |
+
might not reflect changes made after the process started.
|
888 |
+
"""
|
889 |
+
return self._proc.environ()
|
890 |
+
|
891 |
+
if WINDOWS:
|
892 |
+
|
893 |
+
def num_handles(self):
|
894 |
+
"""Return the number of handles opened by this process
|
895 |
+
(Windows only).
|
896 |
+
"""
|
897 |
+
return self._proc.num_handles()
|
898 |
+
|
899 |
+
def num_ctx_switches(self):
|
900 |
+
"""Return the number of voluntary and involuntary context
|
901 |
+
switches performed by this process.
|
902 |
+
"""
|
903 |
+
return self._proc.num_ctx_switches()
|
904 |
+
|
905 |
+
def num_threads(self):
|
906 |
+
"""Return the number of threads used by this process."""
|
907 |
+
return self._proc.num_threads()
|
908 |
+
|
909 |
+
if hasattr(_psplatform.Process, "threads"):
|
910 |
+
|
911 |
+
def threads(self):
|
912 |
+
"""Return threads opened by process as a list of
|
913 |
+
(id, user_time, system_time) namedtuples representing
|
914 |
+
thread id and thread CPU times (user/system).
|
915 |
+
On OpenBSD this method requires root access.
|
916 |
+
"""
|
917 |
+
return self._proc.threads()
|
918 |
+
|
919 |
+
def children(self, recursive=False):
|
920 |
+
"""Return the children of this process as a list of Process
|
921 |
+
instances, pre-emptively checking whether PID has been reused.
|
922 |
+
If *recursive* is True return all the parent descendants.
|
923 |
+
|
924 |
+
Example (A == this process):
|
925 |
+
|
926 |
+
A ─┐
|
927 |
+
│
|
928 |
+
├─ B (child) ─┐
|
929 |
+
│ └─ X (grandchild) ─┐
|
930 |
+
│ └─ Y (great grandchild)
|
931 |
+
├─ C (child)
|
932 |
+
└─ D (child)
|
933 |
+
|
934 |
+
>>> import psutil
|
935 |
+
>>> p = psutil.Process()
|
936 |
+
>>> p.children()
|
937 |
+
B, C, D
|
938 |
+
>>> p.children(recursive=True)
|
939 |
+
B, X, Y, C, D
|
940 |
+
|
941 |
+
Note that in the example above if process X disappears
|
942 |
+
process Y won't be listed as the reference to process A
|
943 |
+
is lost.
|
944 |
+
"""
|
945 |
+
self._raise_if_pid_reused()
|
946 |
+
ppid_map = _ppid_map()
|
947 |
+
ret = []
|
948 |
+
if not recursive:
|
949 |
+
for pid, ppid in ppid_map.items():
|
950 |
+
if ppid == self.pid:
|
951 |
+
try:
|
952 |
+
child = Process(pid)
|
953 |
+
# if child happens to be older than its parent
|
954 |
+
# (self) it means child's PID has been reused
|
955 |
+
if self.create_time() <= child.create_time():
|
956 |
+
ret.append(child)
|
957 |
+
except (NoSuchProcess, ZombieProcess):
|
958 |
+
pass
|
959 |
+
else:
|
960 |
+
# Construct a {pid: [child pids]} dict
|
961 |
+
reverse_ppid_map = collections.defaultdict(list)
|
962 |
+
for pid, ppid in ppid_map.items():
|
963 |
+
reverse_ppid_map[ppid].append(pid)
|
964 |
+
# Recursively traverse that dict, starting from self.pid,
|
965 |
+
# such that we only call Process() on actual children
|
966 |
+
seen = set()
|
967 |
+
stack = [self.pid]
|
968 |
+
while stack:
|
969 |
+
pid = stack.pop()
|
970 |
+
if pid in seen:
|
971 |
+
# Since pids can be reused while the ppid_map is
|
972 |
+
# constructed, there may be rare instances where
|
973 |
+
# there's a cycle in the recorded process "tree".
|
974 |
+
continue
|
975 |
+
seen.add(pid)
|
976 |
+
for child_pid in reverse_ppid_map[pid]:
|
977 |
+
try:
|
978 |
+
child = Process(child_pid)
|
979 |
+
# if child happens to be older than its parent
|
980 |
+
# (self) it means child's PID has been reused
|
981 |
+
intime = self.create_time() <= child.create_time()
|
982 |
+
if intime:
|
983 |
+
ret.append(child)
|
984 |
+
stack.append(child_pid)
|
985 |
+
except (NoSuchProcess, ZombieProcess):
|
986 |
+
pass
|
987 |
+
return ret
|
988 |
+
|
989 |
+
def cpu_percent(self, interval=None):
|
990 |
+
"""Return a float representing the current process CPU
|
991 |
+
utilization as a percentage.
|
992 |
+
|
993 |
+
When *interval* is 0.0 or None (default) compares process times
|
994 |
+
to system CPU times elapsed since last call, returning
|
995 |
+
immediately (non-blocking). That means that the first time
|
996 |
+
this is called it will return a meaningful 0.0 value.
|
997 |
+
|
998 |
+
When *interval* is > 0.0 compares process times to system CPU
|
999 |
+
times elapsed before and after the interval (blocking).
|
1000 |
+
|
1001 |
+
In this case is recommended for accuracy that this function
|
1002 |
+
be called with at least 0.1 seconds between calls.
|
1003 |
+
|
1004 |
+
A value > 100.0 can be returned in case of processes running
|
1005 |
+
multiple threads on different CPU cores.
|
1006 |
+
|
1007 |
+
The returned value is explicitly NOT split evenly between
|
1008 |
+
all available logical CPUs. This means that a busy loop process
|
1009 |
+
running on a system with 2 logical CPUs will be reported as
|
1010 |
+
having 100% CPU utilization instead of 50%.
|
1011 |
+
|
1012 |
+
Examples:
|
1013 |
+
|
1014 |
+
>>> import psutil
|
1015 |
+
>>> p = psutil.Process(os.getpid())
|
1016 |
+
>>> # blocking
|
1017 |
+
>>> p.cpu_percent(interval=1)
|
1018 |
+
2.0
|
1019 |
+
>>> # non-blocking (percentage since last call)
|
1020 |
+
>>> p.cpu_percent(interval=None)
|
1021 |
+
2.9
|
1022 |
+
>>>
|
1023 |
+
"""
|
1024 |
+
blocking = interval is not None and interval > 0.0
|
1025 |
+
if interval is not None and interval < 0:
|
1026 |
+
msg = "interval is not positive (got %r)" % interval
|
1027 |
+
raise ValueError(msg)
|
1028 |
+
num_cpus = cpu_count() or 1
|
1029 |
+
|
1030 |
+
def timer():
|
1031 |
+
return _timer() * num_cpus
|
1032 |
+
|
1033 |
+
if blocking:
|
1034 |
+
st1 = timer()
|
1035 |
+
pt1 = self._proc.cpu_times()
|
1036 |
+
time.sleep(interval)
|
1037 |
+
st2 = timer()
|
1038 |
+
pt2 = self._proc.cpu_times()
|
1039 |
+
else:
|
1040 |
+
st1 = self._last_sys_cpu_times
|
1041 |
+
pt1 = self._last_proc_cpu_times
|
1042 |
+
st2 = timer()
|
1043 |
+
pt2 = self._proc.cpu_times()
|
1044 |
+
if st1 is None or pt1 is None:
|
1045 |
+
self._last_sys_cpu_times = st2
|
1046 |
+
self._last_proc_cpu_times = pt2
|
1047 |
+
return 0.0
|
1048 |
+
|
1049 |
+
delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
|
1050 |
+
delta_time = st2 - st1
|
1051 |
+
# reset values for next call in case of interval == None
|
1052 |
+
self._last_sys_cpu_times = st2
|
1053 |
+
self._last_proc_cpu_times = pt2
|
1054 |
+
|
1055 |
+
try:
|
1056 |
+
# This is the utilization split evenly between all CPUs.
|
1057 |
+
# E.g. a busy loop process on a 2-CPU-cores system at this
|
1058 |
+
# point is reported as 50% instead of 100%.
|
1059 |
+
overall_cpus_percent = (delta_proc / delta_time) * 100
|
1060 |
+
except ZeroDivisionError:
|
1061 |
+
# interval was too low
|
1062 |
+
return 0.0
|
1063 |
+
else:
|
1064 |
+
# Note 1:
|
1065 |
+
# in order to emulate "top" we multiply the value for the num
|
1066 |
+
# of CPU cores. This way the busy process will be reported as
|
1067 |
+
# having 100% (or more) usage.
|
1068 |
+
#
|
1069 |
+
# Note 2:
|
1070 |
+
# taskmgr.exe on Windows differs in that it will show 50%
|
1071 |
+
# instead.
|
1072 |
+
#
|
1073 |
+
# Note 3:
|
1074 |
+
# a percentage > 100 is legitimate as it can result from a
|
1075 |
+
# process with multiple threads running on different CPU
|
1076 |
+
# cores (top does the same), see:
|
1077 |
+
# http://stackoverflow.com/questions/1032357
|
1078 |
+
# https://github.com/giampaolo/psutil/issues/474
|
1079 |
+
single_cpu_percent = overall_cpus_percent * num_cpus
|
1080 |
+
return round(single_cpu_percent, 1)
|
1081 |
+
|
1082 |
+
@memoize_when_activated
|
1083 |
+
def cpu_times(self):
|
1084 |
+
"""Return a (user, system, children_user, children_system)
|
1085 |
+
namedtuple representing the accumulated process time, in
|
1086 |
+
seconds.
|
1087 |
+
This is similar to os.times() but per-process.
|
1088 |
+
On macOS and Windows children_user and children_system are
|
1089 |
+
always set to 0.
|
1090 |
+
"""
|
1091 |
+
return self._proc.cpu_times()
|
1092 |
+
|
1093 |
+
@memoize_when_activated
|
1094 |
+
def memory_info(self):
|
1095 |
+
"""Return a namedtuple with variable fields depending on the
|
1096 |
+
platform, representing memory information about the process.
|
1097 |
+
|
1098 |
+
The "portable" fields available on all platforms are `rss` and `vms`.
|
1099 |
+
|
1100 |
+
All numbers are expressed in bytes.
|
1101 |
+
"""
|
1102 |
+
return self._proc.memory_info()
|
1103 |
+
|
1104 |
+
@_common.deprecated_method(replacement="memory_info")
|
1105 |
+
def memory_info_ex(self):
|
1106 |
+
return self.memory_info()
|
1107 |
+
|
1108 |
+
def memory_full_info(self):
|
1109 |
+
"""This method returns the same information as memory_info(),
|
1110 |
+
plus, on some platform (Linux, macOS, Windows), also provides
|
1111 |
+
additional metrics (USS, PSS and swap).
|
1112 |
+
The additional metrics provide a better representation of actual
|
1113 |
+
process memory usage.
|
1114 |
+
|
1115 |
+
Namely USS is the memory which is unique to a process and which
|
1116 |
+
would be freed if the process was terminated right now.
|
1117 |
+
|
1118 |
+
It does so by passing through the whole process address.
|
1119 |
+
As such it usually requires higher user privileges than
|
1120 |
+
memory_info() and is considerably slower.
|
1121 |
+
"""
|
1122 |
+
return self._proc.memory_full_info()
|
1123 |
+
|
1124 |
+
def memory_percent(self, memtype="rss"):
|
1125 |
+
"""Compare process memory to total physical system memory and
|
1126 |
+
calculate process memory utilization as a percentage.
|
1127 |
+
*memtype* argument is a string that dictates what type of
|
1128 |
+
process memory you want to compare against (defaults to "rss").
|
1129 |
+
The list of available strings can be obtained like this:
|
1130 |
+
|
1131 |
+
>>> psutil.Process().memory_info()._fields
|
1132 |
+
('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
|
1133 |
+
"""
|
1134 |
+
valid_types = list(_psplatform.pfullmem._fields)
|
1135 |
+
if memtype not in valid_types:
|
1136 |
+
msg = "invalid memtype %r; valid types are %r" % (
|
1137 |
+
memtype,
|
1138 |
+
tuple(valid_types),
|
1139 |
+
)
|
1140 |
+
raise ValueError(msg)
|
1141 |
+
fun = (
|
1142 |
+
self.memory_info
|
1143 |
+
if memtype in _psplatform.pmem._fields
|
1144 |
+
else self.memory_full_info
|
1145 |
+
)
|
1146 |
+
metrics = fun()
|
1147 |
+
value = getattr(metrics, memtype)
|
1148 |
+
|
1149 |
+
# use cached value if available
|
1150 |
+
total_phymem = _TOTAL_PHYMEM or virtual_memory().total
|
1151 |
+
if not total_phymem > 0:
|
1152 |
+
# we should never get here
|
1153 |
+
msg = (
|
1154 |
+
"can't calculate process memory percent because total physical"
|
1155 |
+
" system memory is not positive (%r)" % (total_phymem)
|
1156 |
+
)
|
1157 |
+
raise ValueError(msg)
|
1158 |
+
return (value / float(total_phymem)) * 100
|
1159 |
+
|
1160 |
+
if hasattr(_psplatform.Process, "memory_maps"):
|
1161 |
+
|
1162 |
+
def memory_maps(self, grouped=True):
|
1163 |
+
"""Return process' mapped memory regions as a list of namedtuples
|
1164 |
+
whose fields are variable depending on the platform.
|
1165 |
+
|
1166 |
+
If *grouped* is True the mapped regions with the same 'path'
|
1167 |
+
are grouped together and the different memory fields are summed.
|
1168 |
+
|
1169 |
+
If *grouped* is False every mapped region is shown as a single
|
1170 |
+
entity and the namedtuple will also include the mapped region's
|
1171 |
+
address space ('addr') and permission set ('perms').
|
1172 |
+
"""
|
1173 |
+
it = self._proc.memory_maps()
|
1174 |
+
if grouped:
|
1175 |
+
d = {}
|
1176 |
+
for tupl in it:
|
1177 |
+
path = tupl[2]
|
1178 |
+
nums = tupl[3:]
|
1179 |
+
try:
|
1180 |
+
d[path] = map(lambda x, y: x + y, d[path], nums)
|
1181 |
+
except KeyError:
|
1182 |
+
d[path] = nums
|
1183 |
+
nt = _psplatform.pmmap_grouped
|
1184 |
+
return [nt(path, *d[path]) for path in d] # NOQA
|
1185 |
+
else:
|
1186 |
+
nt = _psplatform.pmmap_ext
|
1187 |
+
return [nt(*x) for x in it]
|
1188 |
+
|
1189 |
+
def open_files(self):
|
1190 |
+
"""Return files opened by process as a list of
|
1191 |
+
(path, fd) namedtuples including the absolute file name
|
1192 |
+
and file descriptor number.
|
1193 |
+
"""
|
1194 |
+
return self._proc.open_files()
|
1195 |
+
|
1196 |
+
def connections(self, kind='inet'):
|
1197 |
+
"""Return socket connections opened by process as a list of
|
1198 |
+
(fd, family, type, laddr, raddr, status) namedtuples.
|
1199 |
+
The *kind* parameter filters for connections that match the
|
1200 |
+
following criteria:
|
1201 |
+
|
1202 |
+
+------------+----------------------------------------------------+
|
1203 |
+
| Kind Value | Connections using |
|
1204 |
+
+------------+----------------------------------------------------+
|
1205 |
+
| inet | IPv4 and IPv6 |
|
1206 |
+
| inet4 | IPv4 |
|
1207 |
+
| inet6 | IPv6 |
|
1208 |
+
| tcp | TCP |
|
1209 |
+
| tcp4 | TCP over IPv4 |
|
1210 |
+
| tcp6 | TCP over IPv6 |
|
1211 |
+
| udp | UDP |
|
1212 |
+
| udp4 | UDP over IPv4 |
|
1213 |
+
| udp6 | UDP over IPv6 |
|
1214 |
+
| unix | UNIX socket (both UDP and TCP protocols) |
|
1215 |
+
| all | the sum of all the possible families and protocols |
|
1216 |
+
+------------+----------------------------------------------------+
|
1217 |
+
"""
|
1218 |
+
return self._proc.connections(kind)
|
1219 |
+
|
1220 |
+
# --- signals
|
1221 |
+
|
1222 |
+
if POSIX:
|
1223 |
+
|
1224 |
+
def _send_signal(self, sig):
|
1225 |
+
assert not self.pid < 0, self.pid
|
1226 |
+
self._raise_if_pid_reused()
|
1227 |
+
if self.pid == 0:
|
1228 |
+
# see "man 2 kill"
|
1229 |
+
msg = (
|
1230 |
+
"preventing sending signal to process with PID 0 as it "
|
1231 |
+
"would affect every process in the process group of the "
|
1232 |
+
"calling process (os.getpid()) instead of PID 0"
|
1233 |
+
)
|
1234 |
+
raise ValueError(msg)
|
1235 |
+
try:
|
1236 |
+
os.kill(self.pid, sig)
|
1237 |
+
except ProcessLookupError:
|
1238 |
+
if OPENBSD and pid_exists(self.pid):
|
1239 |
+
# We do this because os.kill() lies in case of
|
1240 |
+
# zombie processes.
|
1241 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
1242 |
+
else:
|
1243 |
+
self._gone = True
|
1244 |
+
raise NoSuchProcess(self.pid, self._name)
|
1245 |
+
except PermissionError:
|
1246 |
+
raise AccessDenied(self.pid, self._name)
|
1247 |
+
|
1248 |
+
def send_signal(self, sig):
|
1249 |
+
"""Send a signal *sig* to process pre-emptively checking
|
1250 |
+
whether PID has been reused (see signal module constants) .
|
1251 |
+
On Windows only SIGTERM is valid and is treated as an alias
|
1252 |
+
for kill().
|
1253 |
+
"""
|
1254 |
+
if POSIX:
|
1255 |
+
self._send_signal(sig)
|
1256 |
+
else: # pragma: no cover
|
1257 |
+
self._raise_if_pid_reused()
|
1258 |
+
if sig != signal.SIGTERM and not self.is_running():
|
1259 |
+
msg = "process no longer exists"
|
1260 |
+
raise NoSuchProcess(self.pid, self._name, msg=msg)
|
1261 |
+
self._proc.send_signal(sig)
|
1262 |
+
|
1263 |
+
def suspend(self):
|
1264 |
+
"""Suspend process execution with SIGSTOP pre-emptively checking
|
1265 |
+
whether PID has been reused.
|
1266 |
+
On Windows this has the effect of suspending all process threads.
|
1267 |
+
"""
|
1268 |
+
if POSIX:
|
1269 |
+
self._send_signal(signal.SIGSTOP)
|
1270 |
+
else: # pragma: no cover
|
1271 |
+
self._raise_if_pid_reused()
|
1272 |
+
self._proc.suspend()
|
1273 |
+
|
1274 |
+
def resume(self):
|
1275 |
+
"""Resume process execution with SIGCONT pre-emptively checking
|
1276 |
+
whether PID has been reused.
|
1277 |
+
On Windows this has the effect of resuming all process threads.
|
1278 |
+
"""
|
1279 |
+
if POSIX:
|
1280 |
+
self._send_signal(signal.SIGCONT)
|
1281 |
+
else: # pragma: no cover
|
1282 |
+
self._raise_if_pid_reused()
|
1283 |
+
self._proc.resume()
|
1284 |
+
|
1285 |
+
def terminate(self):
|
1286 |
+
"""Terminate the process with SIGTERM pre-emptively checking
|
1287 |
+
whether PID has been reused.
|
1288 |
+
On Windows this is an alias for kill().
|
1289 |
+
"""
|
1290 |
+
if POSIX:
|
1291 |
+
self._send_signal(signal.SIGTERM)
|
1292 |
+
else: # pragma: no cover
|
1293 |
+
self._raise_if_pid_reused()
|
1294 |
+
self._proc.kill()
|
1295 |
+
|
1296 |
+
def kill(self):
|
1297 |
+
"""Kill the current process with SIGKILL pre-emptively checking
|
1298 |
+
whether PID has been reused.
|
1299 |
+
"""
|
1300 |
+
if POSIX:
|
1301 |
+
self._send_signal(signal.SIGKILL)
|
1302 |
+
else: # pragma: no cover
|
1303 |
+
self._raise_if_pid_reused()
|
1304 |
+
self._proc.kill()
|
1305 |
+
|
1306 |
+
def wait(self, timeout=None):
|
1307 |
+
"""Wait for process to terminate and, if process is a children
|
1308 |
+
of os.getpid(), also return its exit code, else None.
|
1309 |
+
On Windows there's no such limitation (exit code is always
|
1310 |
+
returned).
|
1311 |
+
|
1312 |
+
If the process is already terminated immediately return None
|
1313 |
+
instead of raising NoSuchProcess.
|
1314 |
+
|
1315 |
+
If *timeout* (in seconds) is specified and process is still
|
1316 |
+
alive raise TimeoutExpired.
|
1317 |
+
|
1318 |
+
To wait for multiple Process(es) use psutil.wait_procs().
|
1319 |
+
"""
|
1320 |
+
if timeout is not None and not timeout >= 0:
|
1321 |
+
msg = "timeout must be a positive integer"
|
1322 |
+
raise ValueError(msg)
|
1323 |
+
if self._exitcode is not _SENTINEL:
|
1324 |
+
return self._exitcode
|
1325 |
+
self._exitcode = self._proc.wait(timeout)
|
1326 |
+
return self._exitcode
|
1327 |
+
|
1328 |
+
|
1329 |
+
# The valid attr names which can be processed by Process.as_dict().
|
1330 |
+
# fmt: off
|
1331 |
+
_as_dict_attrnames = set(
|
1332 |
+
[x for x in dir(Process) if not x.startswith('_') and x not in
|
1333 |
+
{'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
|
1334 |
+
'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit',
|
1335 |
+
'memory_info_ex', 'oneshot'}])
|
1336 |
+
# fmt: on
|
1337 |
+
|
1338 |
+
|
1339 |
+
# =====================================================================
|
1340 |
+
# --- Popen class
|
1341 |
+
# =====================================================================
|
1342 |
+
|
1343 |
+
|
1344 |
+
class Popen(Process):
|
1345 |
+
"""Same as subprocess.Popen, but in addition it provides all
|
1346 |
+
psutil.Process methods in a single class.
|
1347 |
+
For the following methods which are common to both classes, psutil
|
1348 |
+
implementation takes precedence:
|
1349 |
+
|
1350 |
+
* send_signal()
|
1351 |
+
* terminate()
|
1352 |
+
* kill()
|
1353 |
+
|
1354 |
+
This is done in order to avoid killing another process in case its
|
1355 |
+
PID has been reused, fixing BPO-6973.
|
1356 |
+
|
1357 |
+
>>> import psutil
|
1358 |
+
>>> from subprocess import PIPE
|
1359 |
+
>>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
|
1360 |
+
>>> p.name()
|
1361 |
+
'python'
|
1362 |
+
>>> p.uids()
|
1363 |
+
user(real=1000, effective=1000, saved=1000)
|
1364 |
+
>>> p.username()
|
1365 |
+
'giampaolo'
|
1366 |
+
>>> p.communicate()
|
1367 |
+
('hi', None)
|
1368 |
+
>>> p.terminate()
|
1369 |
+
>>> p.wait(timeout=2)
|
1370 |
+
0
|
1371 |
+
>>>
|
1372 |
+
"""
|
1373 |
+
|
1374 |
+
def __init__(self, *args, **kwargs):
|
1375 |
+
# Explicitly avoid to raise NoSuchProcess in case the process
|
1376 |
+
# spawned by subprocess.Popen terminates too quickly, see:
|
1377 |
+
# https://github.com/giampaolo/psutil/issues/193
|
1378 |
+
self.__subproc = subprocess.Popen(*args, **kwargs)
|
1379 |
+
self._init(self.__subproc.pid, _ignore_nsp=True)
|
1380 |
+
|
1381 |
+
def __dir__(self):
|
1382 |
+
return sorted(set(dir(Popen) + dir(subprocess.Popen)))
|
1383 |
+
|
1384 |
+
def __enter__(self):
|
1385 |
+
if hasattr(self.__subproc, '__enter__'):
|
1386 |
+
self.__subproc.__enter__()
|
1387 |
+
return self
|
1388 |
+
|
1389 |
+
def __exit__(self, *args, **kwargs):
|
1390 |
+
if hasattr(self.__subproc, '__exit__'):
|
1391 |
+
return self.__subproc.__exit__(*args, **kwargs)
|
1392 |
+
else:
|
1393 |
+
if self.stdout:
|
1394 |
+
self.stdout.close()
|
1395 |
+
if self.stderr:
|
1396 |
+
self.stderr.close()
|
1397 |
+
try:
|
1398 |
+
# Flushing a BufferedWriter may raise an error.
|
1399 |
+
if self.stdin:
|
1400 |
+
self.stdin.close()
|
1401 |
+
finally:
|
1402 |
+
# Wait for the process to terminate, to avoid zombies.
|
1403 |
+
self.wait()
|
1404 |
+
|
1405 |
+
def __getattribute__(self, name):
|
1406 |
+
try:
|
1407 |
+
return object.__getattribute__(self, name)
|
1408 |
+
except AttributeError:
|
1409 |
+
try:
|
1410 |
+
return object.__getattribute__(self.__subproc, name)
|
1411 |
+
except AttributeError:
|
1412 |
+
msg = "%s instance has no attribute '%s'" % (
|
1413 |
+
self.__class__.__name__,
|
1414 |
+
name,
|
1415 |
+
)
|
1416 |
+
raise AttributeError(msg)
|
1417 |
+
|
1418 |
+
def wait(self, timeout=None):
|
1419 |
+
if self.__subproc.returncode is not None:
|
1420 |
+
return self.__subproc.returncode
|
1421 |
+
ret = super(Popen, self).wait(timeout) # noqa
|
1422 |
+
self.__subproc.returncode = ret
|
1423 |
+
return ret
|
1424 |
+
|
1425 |
+
|
1426 |
+
# =====================================================================
|
1427 |
+
# --- system processes related functions
|
1428 |
+
# =====================================================================
|
1429 |
+
|
1430 |
+
|
1431 |
+
def pids():
|
1432 |
+
"""Return a list of current running PIDs."""
|
1433 |
+
global _LOWEST_PID
|
1434 |
+
ret = sorted(_psplatform.pids())
|
1435 |
+
_LOWEST_PID = ret[0]
|
1436 |
+
return ret
|
1437 |
+
|
1438 |
+
|
1439 |
+
def pid_exists(pid):
|
1440 |
+
"""Return True if given PID exists in the current process list.
|
1441 |
+
This is faster than doing "pid in psutil.pids()" and
|
1442 |
+
should be preferred.
|
1443 |
+
"""
|
1444 |
+
if pid < 0:
|
1445 |
+
return False
|
1446 |
+
elif pid == 0 and POSIX:
|
1447 |
+
# On POSIX we use os.kill() to determine PID existence.
|
1448 |
+
# According to "man 2 kill" PID 0 has a special meaning
|
1449 |
+
# though: it refers to <<every process in the process
|
1450 |
+
# group of the calling process>> and that is not we want
|
1451 |
+
# to do here.
|
1452 |
+
return pid in pids()
|
1453 |
+
else:
|
1454 |
+
return _psplatform.pid_exists(pid)
|
1455 |
+
|
1456 |
+
|
1457 |
+
_pmap = {}
|
1458 |
+
|
1459 |
+
|
1460 |
+
def process_iter(attrs=None, ad_value=None):
|
1461 |
+
"""Return a generator yielding a Process instance for all
|
1462 |
+
running processes.
|
1463 |
+
|
1464 |
+
Every new Process instance is only created once and then cached
|
1465 |
+
into an internal table which is updated every time this is used.
|
1466 |
+
|
1467 |
+
Cached Process instances are checked for identity so that you're
|
1468 |
+
safe in case a PID has been reused by another process, in which
|
1469 |
+
case the cached instance is updated.
|
1470 |
+
|
1471 |
+
The sorting order in which processes are yielded is based on
|
1472 |
+
their PIDs.
|
1473 |
+
|
1474 |
+
*attrs* and *ad_value* have the same meaning as in
|
1475 |
+
Process.as_dict(). If *attrs* is specified as_dict() is called
|
1476 |
+
and the resulting dict is stored as a 'info' attribute attached
|
1477 |
+
to returned Process instance.
|
1478 |
+
If *attrs* is an empty list it will retrieve all process info
|
1479 |
+
(slow).
|
1480 |
+
"""
|
1481 |
+
global _pmap
|
1482 |
+
|
1483 |
+
def add(pid):
|
1484 |
+
proc = Process(pid)
|
1485 |
+
if attrs is not None:
|
1486 |
+
proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value)
|
1487 |
+
pmap[proc.pid] = proc
|
1488 |
+
return proc
|
1489 |
+
|
1490 |
+
def remove(pid):
|
1491 |
+
pmap.pop(pid, None)
|
1492 |
+
|
1493 |
+
pmap = _pmap.copy()
|
1494 |
+
a = set(pids())
|
1495 |
+
b = set(pmap.keys())
|
1496 |
+
new_pids = a - b
|
1497 |
+
gone_pids = b - a
|
1498 |
+
for pid in gone_pids:
|
1499 |
+
remove(pid)
|
1500 |
+
try:
|
1501 |
+
ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items()))
|
1502 |
+
for pid, proc in ls:
|
1503 |
+
try:
|
1504 |
+
if proc is None: # new process
|
1505 |
+
yield add(pid)
|
1506 |
+
else:
|
1507 |
+
# use is_running() to check whether PID has been
|
1508 |
+
# reused by another process in which case yield a
|
1509 |
+
# new Process instance
|
1510 |
+
if proc.is_running():
|
1511 |
+
if attrs is not None:
|
1512 |
+
proc.info = proc.as_dict(
|
1513 |
+
attrs=attrs, ad_value=ad_value
|
1514 |
+
)
|
1515 |
+
yield proc
|
1516 |
+
else:
|
1517 |
+
yield add(pid)
|
1518 |
+
except NoSuchProcess:
|
1519 |
+
remove(pid)
|
1520 |
+
except AccessDenied:
|
1521 |
+
# Process creation time can't be determined hence there's
|
1522 |
+
# no way to tell whether the pid of the cached process
|
1523 |
+
# has been reused. Just return the cached version.
|
1524 |
+
if proc is None and pid in pmap:
|
1525 |
+
try:
|
1526 |
+
yield pmap[pid]
|
1527 |
+
except KeyError:
|
1528 |
+
# If we get here it is likely that 2 threads were
|
1529 |
+
# using process_iter().
|
1530 |
+
pass
|
1531 |
+
else:
|
1532 |
+
raise
|
1533 |
+
finally:
|
1534 |
+
_pmap = pmap
|
1535 |
+
|
1536 |
+
|
1537 |
+
def wait_procs(procs, timeout=None, callback=None):
|
1538 |
+
"""Convenience function which waits for a list of processes to
|
1539 |
+
terminate.
|
1540 |
+
|
1541 |
+
Return a (gone, alive) tuple indicating which processes
|
1542 |
+
are gone and which ones are still alive.
|
1543 |
+
|
1544 |
+
The gone ones will have a new *returncode* attribute indicating
|
1545 |
+
process exit status (may be None).
|
1546 |
+
|
1547 |
+
*callback* is a function which gets called every time a process
|
1548 |
+
terminates (a Process instance is passed as callback argument).
|
1549 |
+
|
1550 |
+
Function will return as soon as all processes terminate or when
|
1551 |
+
*timeout* occurs.
|
1552 |
+
Differently from Process.wait() it will not raise TimeoutExpired if
|
1553 |
+
*timeout* occurs.
|
1554 |
+
|
1555 |
+
Typical use case is:
|
1556 |
+
|
1557 |
+
- send SIGTERM to a list of processes
|
1558 |
+
- give them some time to terminate
|
1559 |
+
- send SIGKILL to those ones which are still alive
|
1560 |
+
|
1561 |
+
Example:
|
1562 |
+
|
1563 |
+
>>> def on_terminate(proc):
|
1564 |
+
... print("process {} terminated".format(proc))
|
1565 |
+
...
|
1566 |
+
>>> for p in procs:
|
1567 |
+
... p.terminate()
|
1568 |
+
...
|
1569 |
+
>>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
|
1570 |
+
>>> for p in alive:
|
1571 |
+
... p.kill()
|
1572 |
+
"""
|
1573 |
+
|
1574 |
+
def check_gone(proc, timeout):
|
1575 |
+
try:
|
1576 |
+
returncode = proc.wait(timeout=timeout)
|
1577 |
+
except TimeoutExpired:
|
1578 |
+
pass
|
1579 |
+
except _SubprocessTimeoutExpired:
|
1580 |
+
pass
|
1581 |
+
else:
|
1582 |
+
if returncode is not None or not proc.is_running():
|
1583 |
+
# Set new Process instance attribute.
|
1584 |
+
proc.returncode = returncode
|
1585 |
+
gone.add(proc)
|
1586 |
+
if callback is not None:
|
1587 |
+
callback(proc)
|
1588 |
+
|
1589 |
+
if timeout is not None and not timeout >= 0:
|
1590 |
+
msg = "timeout must be a positive integer, got %s" % timeout
|
1591 |
+
raise ValueError(msg)
|
1592 |
+
gone = set()
|
1593 |
+
alive = set(procs)
|
1594 |
+
if callback is not None and not callable(callback):
|
1595 |
+
msg = "callback %r is not a callable" % callback
|
1596 |
+
raise TypeError(msg)
|
1597 |
+
if timeout is not None:
|
1598 |
+
deadline = _timer() + timeout
|
1599 |
+
|
1600 |
+
while alive:
|
1601 |
+
if timeout is not None and timeout <= 0:
|
1602 |
+
break
|
1603 |
+
for proc in alive:
|
1604 |
+
# Make sure that every complete iteration (all processes)
|
1605 |
+
# will last max 1 sec.
|
1606 |
+
# We do this because we don't want to wait too long on a
|
1607 |
+
# single process: in case it terminates too late other
|
1608 |
+
# processes may disappear in the meantime and their PID
|
1609 |
+
# reused.
|
1610 |
+
max_timeout = 1.0 / len(alive)
|
1611 |
+
if timeout is not None:
|
1612 |
+
timeout = min((deadline - _timer()), max_timeout)
|
1613 |
+
if timeout <= 0:
|
1614 |
+
break
|
1615 |
+
check_gone(proc, timeout)
|
1616 |
+
else:
|
1617 |
+
check_gone(proc, max_timeout)
|
1618 |
+
alive = alive - gone
|
1619 |
+
|
1620 |
+
if alive:
|
1621 |
+
# Last attempt over processes survived so far.
|
1622 |
+
# timeout == 0 won't make this function wait any further.
|
1623 |
+
for proc in alive:
|
1624 |
+
check_gone(proc, 0)
|
1625 |
+
alive = alive - gone
|
1626 |
+
|
1627 |
+
return (list(gone), list(alive))
|
1628 |
+
|
1629 |
+
|
1630 |
+
# =====================================================================
|
1631 |
+
# --- CPU related functions
|
1632 |
+
# =====================================================================
|
1633 |
+
|
1634 |
+
|
1635 |
+
def cpu_count(logical=True):
|
1636 |
+
"""Return the number of logical CPUs in the system (same as
|
1637 |
+
os.cpu_count() in Python 3.4).
|
1638 |
+
|
1639 |
+
If *logical* is False return the number of physical cores only
|
1640 |
+
(e.g. hyper thread CPUs are excluded).
|
1641 |
+
|
1642 |
+
Return None if undetermined.
|
1643 |
+
|
1644 |
+
The return value is cached after first call.
|
1645 |
+
If desired cache can be cleared like this:
|
1646 |
+
|
1647 |
+
>>> psutil.cpu_count.cache_clear()
|
1648 |
+
"""
|
1649 |
+
if logical:
|
1650 |
+
ret = _psplatform.cpu_count_logical()
|
1651 |
+
else:
|
1652 |
+
ret = _psplatform.cpu_count_cores()
|
1653 |
+
if ret is not None and ret < 1:
|
1654 |
+
ret = None
|
1655 |
+
return ret
|
1656 |
+
|
1657 |
+
|
1658 |
+
def cpu_times(percpu=False):
|
1659 |
+
"""Return system-wide CPU times as a namedtuple.
|
1660 |
+
Every CPU time represents the seconds the CPU has spent in the
|
1661 |
+
given mode. The namedtuple's fields availability varies depending on the
|
1662 |
+
platform:
|
1663 |
+
|
1664 |
+
- user
|
1665 |
+
- system
|
1666 |
+
- idle
|
1667 |
+
- nice (UNIX)
|
1668 |
+
- iowait (Linux)
|
1669 |
+
- irq (Linux, FreeBSD)
|
1670 |
+
- softirq (Linux)
|
1671 |
+
- steal (Linux >= 2.6.11)
|
1672 |
+
- guest (Linux >= 2.6.24)
|
1673 |
+
- guest_nice (Linux >= 3.2.0)
|
1674 |
+
|
1675 |
+
When *percpu* is True return a list of namedtuples for each CPU.
|
1676 |
+
First element of the list refers to first CPU, second element
|
1677 |
+
to second CPU and so on.
|
1678 |
+
The order of the list is consistent across calls.
|
1679 |
+
"""
|
1680 |
+
if not percpu:
|
1681 |
+
return _psplatform.cpu_times()
|
1682 |
+
else:
|
1683 |
+
return _psplatform.per_cpu_times()
|
1684 |
+
|
1685 |
+
|
1686 |
+
try:
|
1687 |
+
_last_cpu_times = {threading.current_thread().ident: cpu_times()}
|
1688 |
+
except Exception: # noqa: BLE001
|
1689 |
+
# Don't want to crash at import time.
|
1690 |
+
_last_cpu_times = {}
|
1691 |
+
|
1692 |
+
try:
|
1693 |
+
_last_per_cpu_times = {
|
1694 |
+
threading.current_thread().ident: cpu_times(percpu=True)
|
1695 |
+
}
|
1696 |
+
except Exception: # noqa: BLE001
|
1697 |
+
# Don't want to crash at import time.
|
1698 |
+
_last_per_cpu_times = {}
|
1699 |
+
|
1700 |
+
|
1701 |
+
def _cpu_tot_time(times):
|
1702 |
+
"""Given a cpu_time() ntuple calculates the total CPU time
|
1703 |
+
(including idle time).
|
1704 |
+
"""
|
1705 |
+
tot = sum(times)
|
1706 |
+
if LINUX:
|
1707 |
+
# On Linux guest times are already accounted in "user" or
|
1708 |
+
# "nice" times, so we subtract them from total.
|
1709 |
+
# Htop does the same. References:
|
1710 |
+
# https://github.com/giampaolo/psutil/pull/940
|
1711 |
+
# http://unix.stackexchange.com/questions/178045
|
1712 |
+
# https://github.com/torvalds/linux/blob/
|
1713 |
+
# 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
|
1714 |
+
# cputime.c#L158
|
1715 |
+
tot -= getattr(times, "guest", 0) # Linux 2.6.24+
|
1716 |
+
tot -= getattr(times, "guest_nice", 0) # Linux 3.2.0+
|
1717 |
+
return tot
|
1718 |
+
|
1719 |
+
|
1720 |
+
def _cpu_busy_time(times):
|
1721 |
+
"""Given a cpu_time() ntuple calculates the busy CPU time.
|
1722 |
+
We do so by subtracting all idle CPU times.
|
1723 |
+
"""
|
1724 |
+
busy = _cpu_tot_time(times)
|
1725 |
+
busy -= times.idle
|
1726 |
+
# Linux: "iowait" is time during which the CPU does not do anything
|
1727 |
+
# (waits for IO to complete). On Linux IO wait is *not* accounted
|
1728 |
+
# in "idle" time so we subtract it. Htop does the same.
|
1729 |
+
# References:
|
1730 |
+
# https://github.com/torvalds/linux/blob/
|
1731 |
+
# 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
|
1732 |
+
busy -= getattr(times, "iowait", 0)
|
1733 |
+
return busy
|
1734 |
+
|
1735 |
+
|
1736 |
+
def _cpu_times_deltas(t1, t2):
|
1737 |
+
assert t1._fields == t2._fields, (t1, t2)
|
1738 |
+
field_deltas = []
|
1739 |
+
for field in _psplatform.scputimes._fields:
|
1740 |
+
field_delta = getattr(t2, field) - getattr(t1, field)
|
1741 |
+
# CPU times are always supposed to increase over time
|
1742 |
+
# or at least remain the same and that's because time
|
1743 |
+
# cannot go backwards.
|
1744 |
+
# Surprisingly sometimes this might not be the case (at
|
1745 |
+
# least on Windows and Linux), see:
|
1746 |
+
# https://github.com/giampaolo/psutil/issues/392
|
1747 |
+
# https://github.com/giampaolo/psutil/issues/645
|
1748 |
+
# https://github.com/giampaolo/psutil/issues/1210
|
1749 |
+
# Trim negative deltas to zero to ignore decreasing fields.
|
1750 |
+
# top does the same. Reference:
|
1751 |
+
# https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063
|
1752 |
+
field_delta = max(0, field_delta)
|
1753 |
+
field_deltas.append(field_delta)
|
1754 |
+
return _psplatform.scputimes(*field_deltas)
|
1755 |
+
|
1756 |
+
|
1757 |
+
def cpu_percent(interval=None, percpu=False):
|
1758 |
+
"""Return a float representing the current system-wide CPU
|
1759 |
+
utilization as a percentage.
|
1760 |
+
|
1761 |
+
When *interval* is > 0.0 compares system CPU times elapsed before
|
1762 |
+
and after the interval (blocking).
|
1763 |
+
|
1764 |
+
When *interval* is 0.0 or None compares system CPU times elapsed
|
1765 |
+
since last call or module import, returning immediately (non
|
1766 |
+
blocking). That means the first time this is called it will
|
1767 |
+
return a meaningless 0.0 value which you should ignore.
|
1768 |
+
In this case is recommended for accuracy that this function be
|
1769 |
+
called with at least 0.1 seconds between calls.
|
1770 |
+
|
1771 |
+
When *percpu* is True returns a list of floats representing the
|
1772 |
+
utilization as a percentage for each CPU.
|
1773 |
+
First element of the list refers to first CPU, second element
|
1774 |
+
to second CPU and so on.
|
1775 |
+
The order of the list is consistent across calls.
|
1776 |
+
|
1777 |
+
Examples:
|
1778 |
+
|
1779 |
+
>>> # blocking, system-wide
|
1780 |
+
>>> psutil.cpu_percent(interval=1)
|
1781 |
+
2.0
|
1782 |
+
>>>
|
1783 |
+
>>> # blocking, per-cpu
|
1784 |
+
>>> psutil.cpu_percent(interval=1, percpu=True)
|
1785 |
+
[2.0, 1.0]
|
1786 |
+
>>>
|
1787 |
+
>>> # non-blocking (percentage since last call)
|
1788 |
+
>>> psutil.cpu_percent(interval=None)
|
1789 |
+
2.9
|
1790 |
+
>>>
|
1791 |
+
"""
|
1792 |
+
tid = threading.current_thread().ident
|
1793 |
+
blocking = interval is not None and interval > 0.0
|
1794 |
+
if interval is not None and interval < 0:
|
1795 |
+
msg = "interval is not positive (got %r)" % interval
|
1796 |
+
raise ValueError(msg)
|
1797 |
+
|
1798 |
+
def calculate(t1, t2):
|
1799 |
+
times_delta = _cpu_times_deltas(t1, t2)
|
1800 |
+
all_delta = _cpu_tot_time(times_delta)
|
1801 |
+
busy_delta = _cpu_busy_time(times_delta)
|
1802 |
+
|
1803 |
+
try:
|
1804 |
+
busy_perc = (busy_delta / all_delta) * 100
|
1805 |
+
except ZeroDivisionError:
|
1806 |
+
return 0.0
|
1807 |
+
else:
|
1808 |
+
return round(busy_perc, 1)
|
1809 |
+
|
1810 |
+
# system-wide usage
|
1811 |
+
if not percpu:
|
1812 |
+
if blocking:
|
1813 |
+
t1 = cpu_times()
|
1814 |
+
time.sleep(interval)
|
1815 |
+
else:
|
1816 |
+
t1 = _last_cpu_times.get(tid) or cpu_times()
|
1817 |
+
_last_cpu_times[tid] = cpu_times()
|
1818 |
+
return calculate(t1, _last_cpu_times[tid])
|
1819 |
+
# per-cpu usage
|
1820 |
+
else:
|
1821 |
+
ret = []
|
1822 |
+
if blocking:
|
1823 |
+
tot1 = cpu_times(percpu=True)
|
1824 |
+
time.sleep(interval)
|
1825 |
+
else:
|
1826 |
+
tot1 = _last_per_cpu_times.get(tid) or cpu_times(percpu=True)
|
1827 |
+
_last_per_cpu_times[tid] = cpu_times(percpu=True)
|
1828 |
+
for t1, t2 in zip(tot1, _last_per_cpu_times[tid]):
|
1829 |
+
ret.append(calculate(t1, t2))
|
1830 |
+
return ret
|
1831 |
+
|
1832 |
+
|
1833 |
+
# Use a separate dict for cpu_times_percent(), so it's independent from
|
1834 |
+
# cpu_percent() and they can both be used within the same program.
|
1835 |
+
_last_cpu_times_2 = _last_cpu_times.copy()
|
1836 |
+
_last_per_cpu_times_2 = _last_per_cpu_times.copy()
|
1837 |
+
|
1838 |
+
|
1839 |
+
def cpu_times_percent(interval=None, percpu=False):
|
1840 |
+
"""Same as cpu_percent() but provides utilization percentages
|
1841 |
+
for each specific CPU time as is returned by cpu_times().
|
1842 |
+
For instance, on Linux we'll get:
|
1843 |
+
|
1844 |
+
>>> cpu_times_percent()
|
1845 |
+
cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
|
1846 |
+
irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
|
1847 |
+
>>>
|
1848 |
+
|
1849 |
+
*interval* and *percpu* arguments have the same meaning as in
|
1850 |
+
cpu_percent().
|
1851 |
+
"""
|
1852 |
+
tid = threading.current_thread().ident
|
1853 |
+
blocking = interval is not None and interval > 0.0
|
1854 |
+
if interval is not None and interval < 0:
|
1855 |
+
msg = "interval is not positive (got %r)" % interval
|
1856 |
+
raise ValueError(msg)
|
1857 |
+
|
1858 |
+
def calculate(t1, t2):
|
1859 |
+
nums = []
|
1860 |
+
times_delta = _cpu_times_deltas(t1, t2)
|
1861 |
+
all_delta = _cpu_tot_time(times_delta)
|
1862 |
+
# "scale" is the value to multiply each delta with to get percentages.
|
1863 |
+
# We use "max" to avoid division by zero (if all_delta is 0, then all
|
1864 |
+
# fields are 0 so percentages will be 0 too. all_delta cannot be a
|
1865 |
+
# fraction because cpu times are integers)
|
1866 |
+
scale = 100.0 / max(1, all_delta)
|
1867 |
+
for field_delta in times_delta:
|
1868 |
+
field_perc = field_delta * scale
|
1869 |
+
field_perc = round(field_perc, 1)
|
1870 |
+
# make sure we don't return negative values or values over 100%
|
1871 |
+
field_perc = min(max(0.0, field_perc), 100.0)
|
1872 |
+
nums.append(field_perc)
|
1873 |
+
return _psplatform.scputimes(*nums)
|
1874 |
+
|
1875 |
+
# system-wide usage
|
1876 |
+
if not percpu:
|
1877 |
+
if blocking:
|
1878 |
+
t1 = cpu_times()
|
1879 |
+
time.sleep(interval)
|
1880 |
+
else:
|
1881 |
+
t1 = _last_cpu_times_2.get(tid) or cpu_times()
|
1882 |
+
_last_cpu_times_2[tid] = cpu_times()
|
1883 |
+
return calculate(t1, _last_cpu_times_2[tid])
|
1884 |
+
# per-cpu usage
|
1885 |
+
else:
|
1886 |
+
ret = []
|
1887 |
+
if blocking:
|
1888 |
+
tot1 = cpu_times(percpu=True)
|
1889 |
+
time.sleep(interval)
|
1890 |
+
else:
|
1891 |
+
tot1 = _last_per_cpu_times_2.get(tid) or cpu_times(percpu=True)
|
1892 |
+
_last_per_cpu_times_2[tid] = cpu_times(percpu=True)
|
1893 |
+
for t1, t2 in zip(tot1, _last_per_cpu_times_2[tid]):
|
1894 |
+
ret.append(calculate(t1, t2))
|
1895 |
+
return ret
|
1896 |
+
|
1897 |
+
|
1898 |
+
def cpu_stats():
|
1899 |
+
"""Return CPU statistics."""
|
1900 |
+
return _psplatform.cpu_stats()
|
1901 |
+
|
1902 |
+
|
1903 |
+
if hasattr(_psplatform, "cpu_freq"):
|
1904 |
+
|
1905 |
+
def cpu_freq(percpu=False):
|
1906 |
+
"""Return CPU frequency as a namedtuple including current,
|
1907 |
+
min and max frequency expressed in Mhz.
|
1908 |
+
|
1909 |
+
If *percpu* is True and the system supports per-cpu frequency
|
1910 |
+
retrieval (Linux only) a list of frequencies is returned for
|
1911 |
+
each CPU. If not a list with one element is returned.
|
1912 |
+
"""
|
1913 |
+
ret = _psplatform.cpu_freq()
|
1914 |
+
if percpu:
|
1915 |
+
return ret
|
1916 |
+
else:
|
1917 |
+
num_cpus = float(len(ret))
|
1918 |
+
if num_cpus == 0:
|
1919 |
+
return None
|
1920 |
+
elif num_cpus == 1:
|
1921 |
+
return ret[0]
|
1922 |
+
else:
|
1923 |
+
currs, mins, maxs = 0.0, 0.0, 0.0
|
1924 |
+
set_none = False
|
1925 |
+
for cpu in ret:
|
1926 |
+
currs += cpu.current
|
1927 |
+
# On Linux if /proc/cpuinfo is used min/max are set
|
1928 |
+
# to None.
|
1929 |
+
if LINUX and cpu.min is None:
|
1930 |
+
set_none = True
|
1931 |
+
continue
|
1932 |
+
mins += cpu.min
|
1933 |
+
maxs += cpu.max
|
1934 |
+
|
1935 |
+
current = currs / num_cpus
|
1936 |
+
|
1937 |
+
if set_none:
|
1938 |
+
min_ = max_ = None
|
1939 |
+
else:
|
1940 |
+
min_ = mins / num_cpus
|
1941 |
+
max_ = maxs / num_cpus
|
1942 |
+
|
1943 |
+
return _common.scpufreq(current, min_, max_)
|
1944 |
+
|
1945 |
+
__all__.append("cpu_freq")
|
1946 |
+
|
1947 |
+
|
1948 |
+
if hasattr(os, "getloadavg") or hasattr(_psplatform, "getloadavg"):
|
1949 |
+
# Perform this hasattr check once on import time to either use the
|
1950 |
+
# platform based code or proxy straight from the os module.
|
1951 |
+
if hasattr(os, "getloadavg"):
|
1952 |
+
getloadavg = os.getloadavg
|
1953 |
+
else:
|
1954 |
+
getloadavg = _psplatform.getloadavg
|
1955 |
+
|
1956 |
+
__all__.append("getloadavg")
|
1957 |
+
|
1958 |
+
|
1959 |
+
# =====================================================================
|
1960 |
+
# --- system memory related functions
|
1961 |
+
# =====================================================================
|
1962 |
+
|
1963 |
+
|
1964 |
+
def virtual_memory():
|
1965 |
+
"""Return statistics about system memory usage as a namedtuple
|
1966 |
+
including the following fields, expressed in bytes:
|
1967 |
+
|
1968 |
+
- total:
|
1969 |
+
total physical memory available.
|
1970 |
+
|
1971 |
+
- available:
|
1972 |
+
the memory that can be given instantly to processes without the
|
1973 |
+
system going into swap.
|
1974 |
+
This is calculated by summing different memory values depending
|
1975 |
+
on the platform and it is supposed to be used to monitor actual
|
1976 |
+
memory usage in a cross platform fashion.
|
1977 |
+
|
1978 |
+
- percent:
|
1979 |
+
the percentage usage calculated as (total - available) / total * 100
|
1980 |
+
|
1981 |
+
- used:
|
1982 |
+
memory used, calculated differently depending on the platform and
|
1983 |
+
designed for informational purposes only:
|
1984 |
+
macOS: active + wired
|
1985 |
+
BSD: active + wired + cached
|
1986 |
+
Linux: total - free
|
1987 |
+
|
1988 |
+
- free:
|
1989 |
+
memory not being used at all (zeroed) that is readily available;
|
1990 |
+
note that this doesn't reflect the actual memory available
|
1991 |
+
(use 'available' instead)
|
1992 |
+
|
1993 |
+
Platform-specific fields:
|
1994 |
+
|
1995 |
+
- active (UNIX):
|
1996 |
+
memory currently in use or very recently used, and so it is in RAM.
|
1997 |
+
|
1998 |
+
- inactive (UNIX):
|
1999 |
+
memory that is marked as not used.
|
2000 |
+
|
2001 |
+
- buffers (BSD, Linux):
|
2002 |
+
cache for things like file system metadata.
|
2003 |
+
|
2004 |
+
- cached (BSD, macOS):
|
2005 |
+
cache for various things.
|
2006 |
+
|
2007 |
+
- wired (macOS, BSD):
|
2008 |
+
memory that is marked to always stay in RAM. It is never moved to disk.
|
2009 |
+
|
2010 |
+
- shared (BSD):
|
2011 |
+
memory that may be simultaneously accessed by multiple processes.
|
2012 |
+
|
2013 |
+
The sum of 'used' and 'available' does not necessarily equal total.
|
2014 |
+
On Windows 'available' and 'free' are the same.
|
2015 |
+
"""
|
2016 |
+
global _TOTAL_PHYMEM
|
2017 |
+
ret = _psplatform.virtual_memory()
|
2018 |
+
# cached for later use in Process.memory_percent()
|
2019 |
+
_TOTAL_PHYMEM = ret.total
|
2020 |
+
return ret
|
2021 |
+
|
2022 |
+
|
2023 |
+
def swap_memory():
|
2024 |
+
"""Return system swap memory statistics as a namedtuple including
|
2025 |
+
the following fields:
|
2026 |
+
|
2027 |
+
- total: total swap memory in bytes
|
2028 |
+
- used: used swap memory in bytes
|
2029 |
+
- free: free swap memory in bytes
|
2030 |
+
- percent: the percentage usage
|
2031 |
+
- sin: no. of bytes the system has swapped in from disk (cumulative)
|
2032 |
+
- sout: no. of bytes the system has swapped out from disk (cumulative)
|
2033 |
+
|
2034 |
+
'sin' and 'sout' on Windows are meaningless and always set to 0.
|
2035 |
+
"""
|
2036 |
+
return _psplatform.swap_memory()
|
2037 |
+
|
2038 |
+
|
2039 |
+
# =====================================================================
|
2040 |
+
# --- disks/paritions related functions
|
2041 |
+
# =====================================================================
|
2042 |
+
|
2043 |
+
|
2044 |
+
def disk_usage(path):
|
2045 |
+
"""Return disk usage statistics about the given *path* as a
|
2046 |
+
namedtuple including total, used and free space expressed in bytes
|
2047 |
+
plus the percentage usage.
|
2048 |
+
"""
|
2049 |
+
return _psplatform.disk_usage(path)
|
2050 |
+
|
2051 |
+
|
2052 |
+
def disk_partitions(all=False):
|
2053 |
+
"""Return mounted partitions as a list of
|
2054 |
+
(device, mountpoint, fstype, opts) namedtuple.
|
2055 |
+
'opts' field is a raw string separated by commas indicating mount
|
2056 |
+
options which may vary depending on the platform.
|
2057 |
+
|
2058 |
+
If *all* parameter is False return physical devices only and ignore
|
2059 |
+
all others.
|
2060 |
+
"""
|
2061 |
+
|
2062 |
+
def pathconf(path, name):
|
2063 |
+
try:
|
2064 |
+
return os.pathconf(path, name)
|
2065 |
+
except (OSError, AttributeError):
|
2066 |
+
pass
|
2067 |
+
|
2068 |
+
ret = _psplatform.disk_partitions(all)
|
2069 |
+
if POSIX:
|
2070 |
+
new = []
|
2071 |
+
for item in ret:
|
2072 |
+
nt = item._replace(
|
2073 |
+
maxfile=pathconf(item.mountpoint, 'PC_NAME_MAX'),
|
2074 |
+
maxpath=pathconf(item.mountpoint, 'PC_PATH_MAX'),
|
2075 |
+
)
|
2076 |
+
new.append(nt)
|
2077 |
+
return new
|
2078 |
+
else:
|
2079 |
+
return ret
|
2080 |
+
|
2081 |
+
|
2082 |
+
def disk_io_counters(perdisk=False, nowrap=True):
|
2083 |
+
"""Return system disk I/O statistics as a namedtuple including
|
2084 |
+
the following fields:
|
2085 |
+
|
2086 |
+
- read_count: number of reads
|
2087 |
+
- write_count: number of writes
|
2088 |
+
- read_bytes: number of bytes read
|
2089 |
+
- write_bytes: number of bytes written
|
2090 |
+
- read_time: time spent reading from disk (in ms)
|
2091 |
+
- write_time: time spent writing to disk (in ms)
|
2092 |
+
|
2093 |
+
Platform specific:
|
2094 |
+
|
2095 |
+
- busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
|
2096 |
+
- read_merged_count (Linux): number of merged reads
|
2097 |
+
- write_merged_count (Linux): number of merged writes
|
2098 |
+
|
2099 |
+
If *perdisk* is True return the same information for every
|
2100 |
+
physical disk installed on the system as a dictionary
|
2101 |
+
with partition names as the keys and the namedtuple
|
2102 |
+
described above as the values.
|
2103 |
+
|
2104 |
+
If *nowrap* is True it detects and adjust the numbers which overflow
|
2105 |
+
and wrap (restart from 0) and add "old value" to "new value" so that
|
2106 |
+
the returned numbers will always be increasing or remain the same,
|
2107 |
+
but never decrease.
|
2108 |
+
"disk_io_counters.cache_clear()" can be used to invalidate the
|
2109 |
+
cache.
|
2110 |
+
|
2111 |
+
On recent Windows versions 'diskperf -y' command may need to be
|
2112 |
+
executed first otherwise this function won't find any disk.
|
2113 |
+
"""
|
2114 |
+
kwargs = dict(perdisk=perdisk) if LINUX else {}
|
2115 |
+
rawdict = _psplatform.disk_io_counters(**kwargs)
|
2116 |
+
if not rawdict:
|
2117 |
+
return {} if perdisk else None
|
2118 |
+
if nowrap:
|
2119 |
+
rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters')
|
2120 |
+
nt = getattr(_psplatform, "sdiskio", _common.sdiskio)
|
2121 |
+
if perdisk:
|
2122 |
+
for disk, fields in rawdict.items():
|
2123 |
+
rawdict[disk] = nt(*fields)
|
2124 |
+
return rawdict
|
2125 |
+
else:
|
2126 |
+
return nt(*(sum(x) for x in zip(*rawdict.values())))
|
2127 |
+
|
2128 |
+
|
2129 |
+
disk_io_counters.cache_clear = functools.partial(
|
2130 |
+
_wrap_numbers.cache_clear, 'psutil.disk_io_counters'
|
2131 |
+
)
|
2132 |
+
disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
|
2133 |
+
|
2134 |
+
|
2135 |
+
# =====================================================================
|
2136 |
+
# --- network related functions
|
2137 |
+
# =====================================================================
|
2138 |
+
|
2139 |
+
|
2140 |
+
def net_io_counters(pernic=False, nowrap=True):
|
2141 |
+
"""Return network I/O statistics as a namedtuple including
|
2142 |
+
the following fields:
|
2143 |
+
|
2144 |
+
- bytes_sent: number of bytes sent
|
2145 |
+
- bytes_recv: number of bytes received
|
2146 |
+
- packets_sent: number of packets sent
|
2147 |
+
- packets_recv: number of packets received
|
2148 |
+
- errin: total number of errors while receiving
|
2149 |
+
- errout: total number of errors while sending
|
2150 |
+
- dropin: total number of incoming packets which were dropped
|
2151 |
+
- dropout: total number of outgoing packets which were dropped
|
2152 |
+
(always 0 on macOS and BSD)
|
2153 |
+
|
2154 |
+
If *pernic* is True return the same information for every
|
2155 |
+
network interface installed on the system as a dictionary
|
2156 |
+
with network interface names as the keys and the namedtuple
|
2157 |
+
described above as the values.
|
2158 |
+
|
2159 |
+
If *nowrap* is True it detects and adjust the numbers which overflow
|
2160 |
+
and wrap (restart from 0) and add "old value" to "new value" so that
|
2161 |
+
the returned numbers will always be increasing or remain the same,
|
2162 |
+
but never decrease.
|
2163 |
+
"net_io_counters.cache_clear()" can be used to invalidate the
|
2164 |
+
cache.
|
2165 |
+
"""
|
2166 |
+
rawdict = _psplatform.net_io_counters()
|
2167 |
+
if not rawdict:
|
2168 |
+
return {} if pernic else None
|
2169 |
+
if nowrap:
|
2170 |
+
rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters')
|
2171 |
+
if pernic:
|
2172 |
+
for nic, fields in rawdict.items():
|
2173 |
+
rawdict[nic] = _common.snetio(*fields)
|
2174 |
+
return rawdict
|
2175 |
+
else:
|
2176 |
+
return _common.snetio(*[sum(x) for x in zip(*rawdict.values())])
|
2177 |
+
|
2178 |
+
|
2179 |
+
net_io_counters.cache_clear = functools.partial(
|
2180 |
+
_wrap_numbers.cache_clear, 'psutil.net_io_counters'
|
2181 |
+
)
|
2182 |
+
net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
|
2183 |
+
|
2184 |
+
|
2185 |
+
def net_connections(kind='inet'):
|
2186 |
+
"""Return system-wide socket connections as a list of
|
2187 |
+
(fd, family, type, laddr, raddr, status, pid) namedtuples.
|
2188 |
+
In case of limited privileges 'fd' and 'pid' may be set to -1
|
2189 |
+
and None respectively.
|
2190 |
+
The *kind* parameter filters for connections that fit the
|
2191 |
+
following criteria:
|
2192 |
+
|
2193 |
+
+------------+----------------------------------------------------+
|
2194 |
+
| Kind Value | Connections using |
|
2195 |
+
+------------+----------------------------------------------------+
|
2196 |
+
| inet | IPv4 and IPv6 |
|
2197 |
+
| inet4 | IPv4 |
|
2198 |
+
| inet6 | IPv6 |
|
2199 |
+
| tcp | TCP |
|
2200 |
+
| tcp4 | TCP over IPv4 |
|
2201 |
+
| tcp6 | TCP over IPv6 |
|
2202 |
+
| udp | UDP |
|
2203 |
+
| udp4 | UDP over IPv4 |
|
2204 |
+
| udp6 | UDP over IPv6 |
|
2205 |
+
| unix | UNIX socket (both UDP and TCP protocols) |
|
2206 |
+
| all | the sum of all the possible families and protocols |
|
2207 |
+
+------------+----------------------------------------------------+
|
2208 |
+
|
2209 |
+
On macOS this function requires root privileges.
|
2210 |
+
"""
|
2211 |
+
return _psplatform.net_connections(kind)
|
2212 |
+
|
2213 |
+
|
2214 |
+
def net_if_addrs():
|
2215 |
+
"""Return the addresses associated to each NIC (network interface
|
2216 |
+
card) installed on the system as a dictionary whose keys are the
|
2217 |
+
NIC names and value is a list of namedtuples for each address
|
2218 |
+
assigned to the NIC. Each namedtuple includes 5 fields:
|
2219 |
+
|
2220 |
+
- family: can be either socket.AF_INET, socket.AF_INET6 or
|
2221 |
+
psutil.AF_LINK, which refers to a MAC address.
|
2222 |
+
- address: is the primary address and it is always set.
|
2223 |
+
- netmask: and 'broadcast' and 'ptp' may be None.
|
2224 |
+
- ptp: stands for "point to point" and references the
|
2225 |
+
destination address on a point to point interface
|
2226 |
+
(typically a VPN).
|
2227 |
+
- broadcast: and *ptp* are mutually exclusive.
|
2228 |
+
|
2229 |
+
Note: you can have more than one address of the same family
|
2230 |
+
associated with each interface.
|
2231 |
+
"""
|
2232 |
+
has_enums = _PY3
|
2233 |
+
if has_enums:
|
2234 |
+
import socket
|
2235 |
+
rawlist = _psplatform.net_if_addrs()
|
2236 |
+
rawlist.sort(key=lambda x: x[1]) # sort by family
|
2237 |
+
ret = collections.defaultdict(list)
|
2238 |
+
for name, fam, addr, mask, broadcast, ptp in rawlist:
|
2239 |
+
if has_enums:
|
2240 |
+
try:
|
2241 |
+
fam = socket.AddressFamily(fam)
|
2242 |
+
except ValueError:
|
2243 |
+
if WINDOWS and fam == -1:
|
2244 |
+
fam = _psplatform.AF_LINK
|
2245 |
+
elif (
|
2246 |
+
hasattr(_psplatform, "AF_LINK")
|
2247 |
+
and fam == _psplatform.AF_LINK
|
2248 |
+
):
|
2249 |
+
# Linux defines AF_LINK as an alias for AF_PACKET.
|
2250 |
+
# We re-set the family here so that repr(family)
|
2251 |
+
# will show AF_LINK rather than AF_PACKET
|
2252 |
+
fam = _psplatform.AF_LINK
|
2253 |
+
if fam == _psplatform.AF_LINK:
|
2254 |
+
# The underlying C function may return an incomplete MAC
|
2255 |
+
# address in which case we fill it with null bytes, see:
|
2256 |
+
# https://github.com/giampaolo/psutil/issues/786
|
2257 |
+
separator = ":" if POSIX else "-"
|
2258 |
+
while addr.count(separator) < 5:
|
2259 |
+
addr += "%s00" % separator
|
2260 |
+
ret[name].append(_common.snicaddr(fam, addr, mask, broadcast, ptp))
|
2261 |
+
return dict(ret)
|
2262 |
+
|
2263 |
+
|
2264 |
+
def net_if_stats():
|
2265 |
+
"""Return information about each NIC (network interface card)
|
2266 |
+
installed on the system as a dictionary whose keys are the
|
2267 |
+
NIC names and value is a namedtuple with the following fields:
|
2268 |
+
|
2269 |
+
- isup: whether the interface is up (bool)
|
2270 |
+
- duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
|
2271 |
+
NIC_DUPLEX_UNKNOWN
|
2272 |
+
- speed: the NIC speed expressed in mega bits (MB); if it can't
|
2273 |
+
be determined (e.g. 'localhost') it will be set to 0.
|
2274 |
+
- mtu: the maximum transmission unit expressed in bytes.
|
2275 |
+
"""
|
2276 |
+
return _psplatform.net_if_stats()
|
2277 |
+
|
2278 |
+
|
2279 |
+
# =====================================================================
|
2280 |
+
# --- sensors
|
2281 |
+
# =====================================================================
|
2282 |
+
|
2283 |
+
|
2284 |
+
# Linux, macOS
|
2285 |
+
if hasattr(_psplatform, "sensors_temperatures"):
|
2286 |
+
|
2287 |
+
def sensors_temperatures(fahrenheit=False):
|
2288 |
+
"""Return hardware temperatures. Each entry is a namedtuple
|
2289 |
+
representing a certain hardware sensor (it may be a CPU, an
|
2290 |
+
hard disk or something else, depending on the OS and its
|
2291 |
+
configuration).
|
2292 |
+
All temperatures are expressed in celsius unless *fahrenheit*
|
2293 |
+
is set to True.
|
2294 |
+
"""
|
2295 |
+
|
2296 |
+
def convert(n):
|
2297 |
+
if n is not None:
|
2298 |
+
return (float(n) * 9 / 5) + 32 if fahrenheit else n
|
2299 |
+
|
2300 |
+
ret = collections.defaultdict(list)
|
2301 |
+
rawdict = _psplatform.sensors_temperatures()
|
2302 |
+
|
2303 |
+
for name, values in rawdict.items():
|
2304 |
+
while values:
|
2305 |
+
label, current, high, critical = values.pop(0)
|
2306 |
+
current = convert(current)
|
2307 |
+
high = convert(high)
|
2308 |
+
critical = convert(critical)
|
2309 |
+
|
2310 |
+
if high and not critical:
|
2311 |
+
critical = high
|
2312 |
+
elif critical and not high:
|
2313 |
+
high = critical
|
2314 |
+
|
2315 |
+
ret[name].append(
|
2316 |
+
_common.shwtemp(label, current, high, critical)
|
2317 |
+
)
|
2318 |
+
|
2319 |
+
return dict(ret)
|
2320 |
+
|
2321 |
+
__all__.append("sensors_temperatures")
|
2322 |
+
|
2323 |
+
|
2324 |
+
# Linux
|
2325 |
+
if hasattr(_psplatform, "sensors_fans"):
|
2326 |
+
|
2327 |
+
def sensors_fans():
|
2328 |
+
"""Return fans speed. Each entry is a namedtuple
|
2329 |
+
representing a certain hardware sensor.
|
2330 |
+
All speed are expressed in RPM (rounds per minute).
|
2331 |
+
"""
|
2332 |
+
return _psplatform.sensors_fans()
|
2333 |
+
|
2334 |
+
__all__.append("sensors_fans")
|
2335 |
+
|
2336 |
+
|
2337 |
+
# Linux, Windows, FreeBSD, macOS
|
2338 |
+
if hasattr(_psplatform, "sensors_battery"):
|
2339 |
+
|
2340 |
+
def sensors_battery():
|
2341 |
+
"""Return battery information. If no battery is installed
|
2342 |
+
returns None.
|
2343 |
+
|
2344 |
+
- percent: battery power left as a percentage.
|
2345 |
+
- secsleft: a rough approximation of how many seconds are left
|
2346 |
+
before the battery runs out of power. May be
|
2347 |
+
POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
|
2348 |
+
- power_plugged: True if the AC power cable is connected.
|
2349 |
+
"""
|
2350 |
+
return _psplatform.sensors_battery()
|
2351 |
+
|
2352 |
+
__all__.append("sensors_battery")
|
2353 |
+
|
2354 |
+
|
2355 |
+
# =====================================================================
|
2356 |
+
# --- other system related functions
|
2357 |
+
# =====================================================================
|
2358 |
+
|
2359 |
+
|
2360 |
+
def boot_time():
|
2361 |
+
"""Return the system boot time expressed in seconds since the epoch."""
|
2362 |
+
# Note: we are not caching this because it is subject to
|
2363 |
+
# system clock updates.
|
2364 |
+
return _psplatform.boot_time()
|
2365 |
+
|
2366 |
+
|
2367 |
+
def users():
|
2368 |
+
"""Return users currently connected on the system as a list of
|
2369 |
+
namedtuples including the following fields.
|
2370 |
+
|
2371 |
+
- user: the name of the user
|
2372 |
+
- terminal: the tty or pseudo-tty associated with the user, if any.
|
2373 |
+
- host: the host name associated with the entry, if any.
|
2374 |
+
- started: the creation time as a floating point number expressed in
|
2375 |
+
seconds since the epoch.
|
2376 |
+
"""
|
2377 |
+
return _psplatform.users()
|
2378 |
+
|
2379 |
+
|
2380 |
+
# =====================================================================
|
2381 |
+
# --- Windows services
|
2382 |
+
# =====================================================================
|
2383 |
+
|
2384 |
+
|
2385 |
+
if WINDOWS:
|
2386 |
+
|
2387 |
+
def win_service_iter():
|
2388 |
+
"""Return a generator yielding a WindowsService instance for all
|
2389 |
+
Windows services installed.
|
2390 |
+
"""
|
2391 |
+
return _psplatform.win_service_iter()
|
2392 |
+
|
2393 |
+
def win_service_get(name):
|
2394 |
+
"""Get a Windows service by *name*.
|
2395 |
+
Raise NoSuchProcess if no service with such name exists.
|
2396 |
+
"""
|
2397 |
+
return _psplatform.win_service_get(name)
|
2398 |
+
|
2399 |
+
|
2400 |
+
# =====================================================================
|
2401 |
+
|
2402 |
+
|
2403 |
+
def _set_debug(value):
|
2404 |
+
"""Enable or disable PSUTIL_DEBUG option, which prints debugging
|
2405 |
+
messages to stderr.
|
2406 |
+
"""
|
2407 |
+
import psutil._common
|
2408 |
+
|
2409 |
+
psutil._common.PSUTIL_DEBUG = bool(value)
|
2410 |
+
_psplatform.cext.set_debug(bool(value))
|
2411 |
+
|
2412 |
+
|
2413 |
+
def test(): # pragma: no cover
|
2414 |
+
from ._common import bytes2human
|
2415 |
+
from ._compat import get_terminal_size
|
2416 |
+
|
2417 |
+
today_day = datetime.date.today()
|
2418 |
+
# fmt: off
|
2419 |
+
templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s"
|
2420 |
+
attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times',
|
2421 |
+
'create_time', 'memory_info', 'status', 'nice', 'username']
|
2422 |
+
print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE", # NOQA
|
2423 |
+
"STATUS", "START", "TIME", "CMDLINE"))
|
2424 |
+
# fmt: on
|
2425 |
+
for p in process_iter(attrs, ad_value=None):
|
2426 |
+
if p.info['create_time']:
|
2427 |
+
ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
|
2428 |
+
if ctime.date() == today_day:
|
2429 |
+
ctime = ctime.strftime("%H:%M")
|
2430 |
+
else:
|
2431 |
+
ctime = ctime.strftime("%b%d")
|
2432 |
+
else:
|
2433 |
+
ctime = ''
|
2434 |
+
if p.info['cpu_times']:
|
2435 |
+
cputime = time.strftime(
|
2436 |
+
"%M:%S", time.localtime(sum(p.info['cpu_times']))
|
2437 |
+
)
|
2438 |
+
else:
|
2439 |
+
cputime = ''
|
2440 |
+
|
2441 |
+
user = p.info['username'] or ''
|
2442 |
+
if not user and POSIX:
|
2443 |
+
try:
|
2444 |
+
user = p.uids()[0]
|
2445 |
+
except Error:
|
2446 |
+
pass
|
2447 |
+
if user and WINDOWS and '\\' in user:
|
2448 |
+
user = user.split('\\')[1]
|
2449 |
+
user = user[:9]
|
2450 |
+
vms = (
|
2451 |
+
bytes2human(p.info['memory_info'].vms)
|
2452 |
+
if p.info['memory_info'] is not None
|
2453 |
+
else ''
|
2454 |
+
)
|
2455 |
+
rss = (
|
2456 |
+
bytes2human(p.info['memory_info'].rss)
|
2457 |
+
if p.info['memory_info'] is not None
|
2458 |
+
else ''
|
2459 |
+
)
|
2460 |
+
memp = (
|
2461 |
+
round(p.info['memory_percent'], 1)
|
2462 |
+
if p.info['memory_percent'] is not None
|
2463 |
+
else ''
|
2464 |
+
)
|
2465 |
+
nice = int(p.info['nice']) if p.info['nice'] else ''
|
2466 |
+
if p.info['cmdline']:
|
2467 |
+
cmdline = ' '.join(p.info['cmdline'])
|
2468 |
+
else:
|
2469 |
+
cmdline = p.info['name']
|
2470 |
+
status = p.info['status'][:5] if p.info['status'] else ''
|
2471 |
+
|
2472 |
+
line = templ % (
|
2473 |
+
user[:10],
|
2474 |
+
p.info['pid'],
|
2475 |
+
memp,
|
2476 |
+
vms,
|
2477 |
+
rss,
|
2478 |
+
nice,
|
2479 |
+
status,
|
2480 |
+
ctime,
|
2481 |
+
cputime,
|
2482 |
+
cmdline,
|
2483 |
+
)
|
2484 |
+
print(line[: get_terminal_size()[0]]) # NOQA
|
2485 |
+
|
2486 |
+
|
2487 |
+
del memoize_when_activated, division
|
2488 |
+
if sys.version_info[0] < 3:
|
2489 |
+
del num, x # noqa
|
2490 |
+
|
2491 |
+
if __name__ == "__main__":
|
2492 |
+
test()
|
env-llmeval/lib/python3.10/site-packages/psutil/__pycache__/_psosx.cpython-310.pyc
ADDED
Binary file (13.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/_common.py
ADDED
@@ -0,0 +1,983 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""Common objects shared by __init__.py and _ps*.py modules."""
|
6 |
+
|
7 |
+
# Note: this module is imported by setup.py so it should not import
|
8 |
+
# psutil or third-party modules.
|
9 |
+
|
10 |
+
from __future__ import division
|
11 |
+
from __future__ import print_function
|
12 |
+
|
13 |
+
import collections
|
14 |
+
import contextlib
|
15 |
+
import errno
|
16 |
+
import functools
|
17 |
+
import os
|
18 |
+
import socket
|
19 |
+
import stat
|
20 |
+
import sys
|
21 |
+
import threading
|
22 |
+
import warnings
|
23 |
+
from collections import namedtuple
|
24 |
+
from socket import AF_INET
|
25 |
+
from socket import SOCK_DGRAM
|
26 |
+
from socket import SOCK_STREAM
|
27 |
+
|
28 |
+
|
29 |
+
try:
|
30 |
+
from socket import AF_INET6
|
31 |
+
except ImportError:
|
32 |
+
AF_INET6 = None
|
33 |
+
try:
|
34 |
+
from socket import AF_UNIX
|
35 |
+
except ImportError:
|
36 |
+
AF_UNIX = None
|
37 |
+
|
38 |
+
|
39 |
+
# can't take it from _common.py as this script is imported by setup.py
|
40 |
+
PY3 = sys.version_info[0] >= 3
|
41 |
+
if PY3:
|
42 |
+
import enum
|
43 |
+
else:
|
44 |
+
enum = None
|
45 |
+
|
46 |
+
|
47 |
+
PSUTIL_DEBUG = bool(os.getenv('PSUTIL_DEBUG'))
|
48 |
+
_DEFAULT = object()
|
49 |
+
|
50 |
+
# fmt: off
|
51 |
+
__all__ = [
|
52 |
+
# OS constants
|
53 |
+
'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'MACOS', 'OSX', 'POSIX',
|
54 |
+
'SUNOS', 'WINDOWS',
|
55 |
+
# connection constants
|
56 |
+
'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED',
|
57 |
+
'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN',
|
58 |
+
'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT',
|
59 |
+
# net constants
|
60 |
+
'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN',
|
61 |
+
# process status constants
|
62 |
+
'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED',
|
63 |
+
'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED',
|
64 |
+
'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL',
|
65 |
+
'STATUS_WAKING', 'STATUS_ZOMBIE', 'STATUS_PARKED',
|
66 |
+
# other constants
|
67 |
+
'ENCODING', 'ENCODING_ERRS', 'AF_INET6',
|
68 |
+
# named tuples
|
69 |
+
'pconn', 'pcputimes', 'pctxsw', 'pgids', 'pio', 'pionice', 'popenfile',
|
70 |
+
'pthread', 'puids', 'sconn', 'scpustats', 'sdiskio', 'sdiskpart',
|
71 |
+
'sdiskusage', 'snetio', 'snicaddr', 'snicstats', 'sswap', 'suser',
|
72 |
+
# utility functions
|
73 |
+
'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize',
|
74 |
+
'parse_environ_block', 'path_exists_strict', 'usage_percent',
|
75 |
+
'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers",
|
76 |
+
'open_text', 'open_binary', 'cat', 'bcat',
|
77 |
+
'bytes2human', 'conn_to_ntuple', 'debug',
|
78 |
+
# shell utils
|
79 |
+
'hilite', 'term_supports_colors', 'print_color',
|
80 |
+
]
|
81 |
+
# fmt: on
|
82 |
+
|
83 |
+
|
84 |
+
# ===================================================================
|
85 |
+
# --- OS constants
|
86 |
+
# ===================================================================
|
87 |
+
|
88 |
+
|
89 |
+
POSIX = os.name == "posix"
|
90 |
+
WINDOWS = os.name == "nt"
|
91 |
+
LINUX = sys.platform.startswith("linux")
|
92 |
+
MACOS = sys.platform.startswith("darwin")
|
93 |
+
OSX = MACOS # deprecated alias
|
94 |
+
FREEBSD = sys.platform.startswith(("freebsd", "midnightbsd"))
|
95 |
+
OPENBSD = sys.platform.startswith("openbsd")
|
96 |
+
NETBSD = sys.platform.startswith("netbsd")
|
97 |
+
BSD = FREEBSD or OPENBSD or NETBSD
|
98 |
+
SUNOS = sys.platform.startswith(("sunos", "solaris"))
|
99 |
+
AIX = sys.platform.startswith("aix")
|
100 |
+
|
101 |
+
|
102 |
+
# ===================================================================
|
103 |
+
# --- API constants
|
104 |
+
# ===================================================================
|
105 |
+
|
106 |
+
|
107 |
+
# Process.status()
|
108 |
+
STATUS_RUNNING = "running"
|
109 |
+
STATUS_SLEEPING = "sleeping"
|
110 |
+
STATUS_DISK_SLEEP = "disk-sleep"
|
111 |
+
STATUS_STOPPED = "stopped"
|
112 |
+
STATUS_TRACING_STOP = "tracing-stop"
|
113 |
+
STATUS_ZOMBIE = "zombie"
|
114 |
+
STATUS_DEAD = "dead"
|
115 |
+
STATUS_WAKE_KILL = "wake-kill"
|
116 |
+
STATUS_WAKING = "waking"
|
117 |
+
STATUS_IDLE = "idle" # Linux, macOS, FreeBSD
|
118 |
+
STATUS_LOCKED = "locked" # FreeBSD
|
119 |
+
STATUS_WAITING = "waiting" # FreeBSD
|
120 |
+
STATUS_SUSPENDED = "suspended" # NetBSD
|
121 |
+
STATUS_PARKED = "parked" # Linux
|
122 |
+
|
123 |
+
# Process.connections() and psutil.net_connections()
|
124 |
+
CONN_ESTABLISHED = "ESTABLISHED"
|
125 |
+
CONN_SYN_SENT = "SYN_SENT"
|
126 |
+
CONN_SYN_RECV = "SYN_RECV"
|
127 |
+
CONN_FIN_WAIT1 = "FIN_WAIT1"
|
128 |
+
CONN_FIN_WAIT2 = "FIN_WAIT2"
|
129 |
+
CONN_TIME_WAIT = "TIME_WAIT"
|
130 |
+
CONN_CLOSE = "CLOSE"
|
131 |
+
CONN_CLOSE_WAIT = "CLOSE_WAIT"
|
132 |
+
CONN_LAST_ACK = "LAST_ACK"
|
133 |
+
CONN_LISTEN = "LISTEN"
|
134 |
+
CONN_CLOSING = "CLOSING"
|
135 |
+
CONN_NONE = "NONE"
|
136 |
+
|
137 |
+
# net_if_stats()
|
138 |
+
if enum is None:
|
139 |
+
NIC_DUPLEX_FULL = 2
|
140 |
+
NIC_DUPLEX_HALF = 1
|
141 |
+
NIC_DUPLEX_UNKNOWN = 0
|
142 |
+
else:
|
143 |
+
|
144 |
+
class NicDuplex(enum.IntEnum):
|
145 |
+
NIC_DUPLEX_FULL = 2
|
146 |
+
NIC_DUPLEX_HALF = 1
|
147 |
+
NIC_DUPLEX_UNKNOWN = 0
|
148 |
+
|
149 |
+
globals().update(NicDuplex.__members__)
|
150 |
+
|
151 |
+
# sensors_battery()
|
152 |
+
if enum is None:
|
153 |
+
POWER_TIME_UNKNOWN = -1
|
154 |
+
POWER_TIME_UNLIMITED = -2
|
155 |
+
else:
|
156 |
+
|
157 |
+
class BatteryTime(enum.IntEnum):
|
158 |
+
POWER_TIME_UNKNOWN = -1
|
159 |
+
POWER_TIME_UNLIMITED = -2
|
160 |
+
|
161 |
+
globals().update(BatteryTime.__members__)
|
162 |
+
|
163 |
+
# --- others
|
164 |
+
|
165 |
+
ENCODING = sys.getfilesystemencoding()
|
166 |
+
if not PY3:
|
167 |
+
ENCODING_ERRS = "replace"
|
168 |
+
else:
|
169 |
+
try:
|
170 |
+
ENCODING_ERRS = sys.getfilesystemencodeerrors() # py 3.6
|
171 |
+
except AttributeError:
|
172 |
+
ENCODING_ERRS = "surrogateescape" if POSIX else "replace"
|
173 |
+
|
174 |
+
|
175 |
+
# ===================================================================
|
176 |
+
# --- namedtuples
|
177 |
+
# ===================================================================
|
178 |
+
|
179 |
+
# --- for system functions
|
180 |
+
|
181 |
+
# fmt: off
|
182 |
+
# psutil.swap_memory()
|
183 |
+
sswap = namedtuple('sswap', ['total', 'used', 'free', 'percent', 'sin',
|
184 |
+
'sout'])
|
185 |
+
# psutil.disk_usage()
|
186 |
+
sdiskusage = namedtuple('sdiskusage', ['total', 'used', 'free', 'percent'])
|
187 |
+
# psutil.disk_io_counters()
|
188 |
+
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
189 |
+
'read_bytes', 'write_bytes',
|
190 |
+
'read_time', 'write_time'])
|
191 |
+
# psutil.disk_partitions()
|
192 |
+
sdiskpart = namedtuple('sdiskpart', ['device', 'mountpoint', 'fstype', 'opts',
|
193 |
+
'maxfile', 'maxpath'])
|
194 |
+
# psutil.net_io_counters()
|
195 |
+
snetio = namedtuple('snetio', ['bytes_sent', 'bytes_recv',
|
196 |
+
'packets_sent', 'packets_recv',
|
197 |
+
'errin', 'errout',
|
198 |
+
'dropin', 'dropout'])
|
199 |
+
# psutil.users()
|
200 |
+
suser = namedtuple('suser', ['name', 'terminal', 'host', 'started', 'pid'])
|
201 |
+
# psutil.net_connections()
|
202 |
+
sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr',
|
203 |
+
'status', 'pid'])
|
204 |
+
# psutil.net_if_addrs()
|
205 |
+
snicaddr = namedtuple('snicaddr',
|
206 |
+
['family', 'address', 'netmask', 'broadcast', 'ptp'])
|
207 |
+
# psutil.net_if_stats()
|
208 |
+
snicstats = namedtuple('snicstats',
|
209 |
+
['isup', 'duplex', 'speed', 'mtu', 'flags'])
|
210 |
+
# psutil.cpu_stats()
|
211 |
+
scpustats = namedtuple(
|
212 |
+
'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'])
|
213 |
+
# psutil.cpu_freq()
|
214 |
+
scpufreq = namedtuple('scpufreq', ['current', 'min', 'max'])
|
215 |
+
# psutil.sensors_temperatures()
|
216 |
+
shwtemp = namedtuple(
|
217 |
+
'shwtemp', ['label', 'current', 'high', 'critical'])
|
218 |
+
# psutil.sensors_battery()
|
219 |
+
sbattery = namedtuple('sbattery', ['percent', 'secsleft', 'power_plugged'])
|
220 |
+
# psutil.sensors_fans()
|
221 |
+
sfan = namedtuple('sfan', ['label', 'current'])
|
222 |
+
# fmt: on
|
223 |
+
|
224 |
+
# --- for Process methods
|
225 |
+
|
226 |
+
# psutil.Process.cpu_times()
|
227 |
+
pcputimes = namedtuple(
|
228 |
+
'pcputimes', ['user', 'system', 'children_user', 'children_system']
|
229 |
+
)
|
230 |
+
# psutil.Process.open_files()
|
231 |
+
popenfile = namedtuple('popenfile', ['path', 'fd'])
|
232 |
+
# psutil.Process.threads()
|
233 |
+
pthread = namedtuple('pthread', ['id', 'user_time', 'system_time'])
|
234 |
+
# psutil.Process.uids()
|
235 |
+
puids = namedtuple('puids', ['real', 'effective', 'saved'])
|
236 |
+
# psutil.Process.gids()
|
237 |
+
pgids = namedtuple('pgids', ['real', 'effective', 'saved'])
|
238 |
+
# psutil.Process.io_counters()
|
239 |
+
pio = namedtuple(
|
240 |
+
'pio', ['read_count', 'write_count', 'read_bytes', 'write_bytes']
|
241 |
+
)
|
242 |
+
# psutil.Process.ionice()
|
243 |
+
pionice = namedtuple('pionice', ['ioclass', 'value'])
|
244 |
+
# psutil.Process.ctx_switches()
|
245 |
+
pctxsw = namedtuple('pctxsw', ['voluntary', 'involuntary'])
|
246 |
+
# psutil.Process.connections()
|
247 |
+
pconn = namedtuple(
|
248 |
+
'pconn', ['fd', 'family', 'type', 'laddr', 'raddr', 'status']
|
249 |
+
)
|
250 |
+
|
251 |
+
# psutil.connections() and psutil.Process.connections()
|
252 |
+
addr = namedtuple('addr', ['ip', 'port'])
|
253 |
+
|
254 |
+
|
255 |
+
# ===================================================================
|
256 |
+
# --- Process.connections() 'kind' parameter mapping
|
257 |
+
# ===================================================================
|
258 |
+
|
259 |
+
|
260 |
+
conn_tmap = {
|
261 |
+
"all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
|
262 |
+
"tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]),
|
263 |
+
"tcp4": ([AF_INET], [SOCK_STREAM]),
|
264 |
+
"udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]),
|
265 |
+
"udp4": ([AF_INET], [SOCK_DGRAM]),
|
266 |
+
"inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
|
267 |
+
"inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]),
|
268 |
+
"inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
|
269 |
+
}
|
270 |
+
|
271 |
+
if AF_INET6 is not None:
|
272 |
+
conn_tmap.update({
|
273 |
+
"tcp6": ([AF_INET6], [SOCK_STREAM]),
|
274 |
+
"udp6": ([AF_INET6], [SOCK_DGRAM]),
|
275 |
+
})
|
276 |
+
|
277 |
+
if AF_UNIX is not None:
|
278 |
+
conn_tmap.update({"unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM])})
|
279 |
+
|
280 |
+
|
281 |
+
# =====================================================================
|
282 |
+
# --- Exceptions
|
283 |
+
# =====================================================================
|
284 |
+
|
285 |
+
|
286 |
+
class Error(Exception):
|
287 |
+
"""Base exception class. All other psutil exceptions inherit
|
288 |
+
from this one.
|
289 |
+
"""
|
290 |
+
|
291 |
+
__module__ = 'psutil'
|
292 |
+
|
293 |
+
def _infodict(self, attrs):
|
294 |
+
info = collections.OrderedDict()
|
295 |
+
for name in attrs:
|
296 |
+
value = getattr(self, name, None)
|
297 |
+
if value: # noqa
|
298 |
+
info[name] = value
|
299 |
+
elif name == "pid" and value == 0:
|
300 |
+
info[name] = value
|
301 |
+
return info
|
302 |
+
|
303 |
+
def __str__(self):
|
304 |
+
# invoked on `raise Error`
|
305 |
+
info = self._infodict(("pid", "ppid", "name"))
|
306 |
+
if info:
|
307 |
+
details = "(%s)" % ", ".join(
|
308 |
+
["%s=%r" % (k, v) for k, v in info.items()]
|
309 |
+
)
|
310 |
+
else:
|
311 |
+
details = None
|
312 |
+
return " ".join([x for x in (getattr(self, "msg", ""), details) if x])
|
313 |
+
|
314 |
+
def __repr__(self):
|
315 |
+
# invoked on `repr(Error)`
|
316 |
+
info = self._infodict(("pid", "ppid", "name", "seconds", "msg"))
|
317 |
+
details = ", ".join(["%s=%r" % (k, v) for k, v in info.items()])
|
318 |
+
return "psutil.%s(%s)" % (self.__class__.__name__, details)
|
319 |
+
|
320 |
+
|
321 |
+
class NoSuchProcess(Error):
|
322 |
+
"""Exception raised when a process with a certain PID doesn't
|
323 |
+
or no longer exists.
|
324 |
+
"""
|
325 |
+
|
326 |
+
__module__ = 'psutil'
|
327 |
+
|
328 |
+
def __init__(self, pid, name=None, msg=None):
|
329 |
+
Error.__init__(self)
|
330 |
+
self.pid = pid
|
331 |
+
self.name = name
|
332 |
+
self.msg = msg or "process no longer exists"
|
333 |
+
|
334 |
+
|
335 |
+
class ZombieProcess(NoSuchProcess):
|
336 |
+
"""Exception raised when querying a zombie process. This is
|
337 |
+
raised on macOS, BSD and Solaris only, and not always: depending
|
338 |
+
on the query the OS may be able to succeed anyway.
|
339 |
+
On Linux all zombie processes are querable (hence this is never
|
340 |
+
raised). Windows doesn't have zombie processes.
|
341 |
+
"""
|
342 |
+
|
343 |
+
__module__ = 'psutil'
|
344 |
+
|
345 |
+
def __init__(self, pid, name=None, ppid=None, msg=None):
|
346 |
+
NoSuchProcess.__init__(self, pid, name, msg)
|
347 |
+
self.ppid = ppid
|
348 |
+
self.msg = msg or "PID still exists but it's a zombie"
|
349 |
+
|
350 |
+
|
351 |
+
class AccessDenied(Error):
|
352 |
+
"""Exception raised when permission to perform an action is denied."""
|
353 |
+
|
354 |
+
__module__ = 'psutil'
|
355 |
+
|
356 |
+
def __init__(self, pid=None, name=None, msg=None):
|
357 |
+
Error.__init__(self)
|
358 |
+
self.pid = pid
|
359 |
+
self.name = name
|
360 |
+
self.msg = msg or ""
|
361 |
+
|
362 |
+
|
363 |
+
class TimeoutExpired(Error):
|
364 |
+
"""Raised on Process.wait(timeout) if timeout expires and process
|
365 |
+
is still alive.
|
366 |
+
"""
|
367 |
+
|
368 |
+
__module__ = 'psutil'
|
369 |
+
|
370 |
+
def __init__(self, seconds, pid=None, name=None):
|
371 |
+
Error.__init__(self)
|
372 |
+
self.seconds = seconds
|
373 |
+
self.pid = pid
|
374 |
+
self.name = name
|
375 |
+
self.msg = "timeout after %s seconds" % seconds
|
376 |
+
|
377 |
+
|
378 |
+
# ===================================================================
|
379 |
+
# --- utils
|
380 |
+
# ===================================================================
|
381 |
+
|
382 |
+
|
383 |
+
# This should be in _compat.py rather than here, but does not work well
|
384 |
+
# with setup.py importing this module via a sys.path trick.
|
385 |
+
if PY3:
|
386 |
+
if isinstance(__builtins__, dict): # cpython
|
387 |
+
exec_ = __builtins__["exec"]
|
388 |
+
else: # pypy
|
389 |
+
exec_ = getattr(__builtins__, "exec") # noqa
|
390 |
+
|
391 |
+
exec_("""def raise_from(value, from_value):
|
392 |
+
try:
|
393 |
+
raise value from from_value
|
394 |
+
finally:
|
395 |
+
value = None
|
396 |
+
""")
|
397 |
+
else:
|
398 |
+
|
399 |
+
def raise_from(value, from_value):
|
400 |
+
raise value
|
401 |
+
|
402 |
+
|
403 |
+
def usage_percent(used, total, round_=None):
|
404 |
+
"""Calculate percentage usage of 'used' against 'total'."""
|
405 |
+
try:
|
406 |
+
ret = (float(used) / total) * 100
|
407 |
+
except ZeroDivisionError:
|
408 |
+
return 0.0
|
409 |
+
else:
|
410 |
+
if round_ is not None:
|
411 |
+
ret = round(ret, round_)
|
412 |
+
return ret
|
413 |
+
|
414 |
+
|
415 |
+
def memoize(fun):
|
416 |
+
"""A simple memoize decorator for functions supporting (hashable)
|
417 |
+
positional arguments.
|
418 |
+
It also provides a cache_clear() function for clearing the cache:
|
419 |
+
|
420 |
+
>>> @memoize
|
421 |
+
... def foo()
|
422 |
+
... return 1
|
423 |
+
...
|
424 |
+
>>> foo()
|
425 |
+
1
|
426 |
+
>>> foo.cache_clear()
|
427 |
+
>>>
|
428 |
+
|
429 |
+
It supports:
|
430 |
+
- functions
|
431 |
+
- classes (acts as a @singleton)
|
432 |
+
- staticmethods
|
433 |
+
- classmethods
|
434 |
+
|
435 |
+
It does NOT support:
|
436 |
+
- methods
|
437 |
+
"""
|
438 |
+
|
439 |
+
@functools.wraps(fun)
|
440 |
+
def wrapper(*args, **kwargs):
|
441 |
+
key = (args, frozenset(sorted(kwargs.items())))
|
442 |
+
try:
|
443 |
+
return cache[key]
|
444 |
+
except KeyError:
|
445 |
+
try:
|
446 |
+
ret = cache[key] = fun(*args, **kwargs)
|
447 |
+
except Exception as err: # noqa: BLE001
|
448 |
+
raise raise_from(err, None)
|
449 |
+
return ret
|
450 |
+
|
451 |
+
def cache_clear():
|
452 |
+
"""Clear cache."""
|
453 |
+
cache.clear()
|
454 |
+
|
455 |
+
cache = {}
|
456 |
+
wrapper.cache_clear = cache_clear
|
457 |
+
return wrapper
|
458 |
+
|
459 |
+
|
460 |
+
def memoize_when_activated(fun):
|
461 |
+
"""A memoize decorator which is disabled by default. It can be
|
462 |
+
activated and deactivated on request.
|
463 |
+
For efficiency reasons it can be used only against class methods
|
464 |
+
accepting no arguments.
|
465 |
+
|
466 |
+
>>> class Foo:
|
467 |
+
... @memoize
|
468 |
+
... def foo()
|
469 |
+
... print(1)
|
470 |
+
...
|
471 |
+
>>> f = Foo()
|
472 |
+
>>> # deactivated (default)
|
473 |
+
>>> foo()
|
474 |
+
1
|
475 |
+
>>> foo()
|
476 |
+
1
|
477 |
+
>>>
|
478 |
+
>>> # activated
|
479 |
+
>>> foo.cache_activate(self)
|
480 |
+
>>> foo()
|
481 |
+
1
|
482 |
+
>>> foo()
|
483 |
+
>>> foo()
|
484 |
+
>>>
|
485 |
+
"""
|
486 |
+
|
487 |
+
@functools.wraps(fun)
|
488 |
+
def wrapper(self):
|
489 |
+
try:
|
490 |
+
# case 1: we previously entered oneshot() ctx
|
491 |
+
ret = self._cache[fun]
|
492 |
+
except AttributeError:
|
493 |
+
# case 2: we never entered oneshot() ctx
|
494 |
+
try:
|
495 |
+
return fun(self)
|
496 |
+
except Exception as err: # noqa: BLE001
|
497 |
+
raise raise_from(err, None)
|
498 |
+
except KeyError:
|
499 |
+
# case 3: we entered oneshot() ctx but there's no cache
|
500 |
+
# for this entry yet
|
501 |
+
try:
|
502 |
+
ret = fun(self)
|
503 |
+
except Exception as err: # noqa: BLE001
|
504 |
+
raise raise_from(err, None)
|
505 |
+
try:
|
506 |
+
self._cache[fun] = ret
|
507 |
+
except AttributeError:
|
508 |
+
# multi-threading race condition, see:
|
509 |
+
# https://github.com/giampaolo/psutil/issues/1948
|
510 |
+
pass
|
511 |
+
return ret
|
512 |
+
|
513 |
+
def cache_activate(proc):
|
514 |
+
"""Activate cache. Expects a Process instance. Cache will be
|
515 |
+
stored as a "_cache" instance attribute.
|
516 |
+
"""
|
517 |
+
proc._cache = {}
|
518 |
+
|
519 |
+
def cache_deactivate(proc):
|
520 |
+
"""Deactivate and clear cache."""
|
521 |
+
try:
|
522 |
+
del proc._cache
|
523 |
+
except AttributeError:
|
524 |
+
pass
|
525 |
+
|
526 |
+
wrapper.cache_activate = cache_activate
|
527 |
+
wrapper.cache_deactivate = cache_deactivate
|
528 |
+
return wrapper
|
529 |
+
|
530 |
+
|
531 |
+
def isfile_strict(path):
|
532 |
+
"""Same as os.path.isfile() but does not swallow EACCES / EPERM
|
533 |
+
exceptions, see:
|
534 |
+
http://mail.python.org/pipermail/python-dev/2012-June/120787.html.
|
535 |
+
"""
|
536 |
+
try:
|
537 |
+
st = os.stat(path)
|
538 |
+
except OSError as err:
|
539 |
+
if err.errno in (errno.EPERM, errno.EACCES):
|
540 |
+
raise
|
541 |
+
return False
|
542 |
+
else:
|
543 |
+
return stat.S_ISREG(st.st_mode)
|
544 |
+
|
545 |
+
|
546 |
+
def path_exists_strict(path):
|
547 |
+
"""Same as os.path.exists() but does not swallow EACCES / EPERM
|
548 |
+
exceptions. See:
|
549 |
+
http://mail.python.org/pipermail/python-dev/2012-June/120787.html.
|
550 |
+
"""
|
551 |
+
try:
|
552 |
+
os.stat(path)
|
553 |
+
except OSError as err:
|
554 |
+
if err.errno in (errno.EPERM, errno.EACCES):
|
555 |
+
raise
|
556 |
+
return False
|
557 |
+
else:
|
558 |
+
return True
|
559 |
+
|
560 |
+
|
561 |
+
@memoize
|
562 |
+
def supports_ipv6():
|
563 |
+
"""Return True if IPv6 is supported on this platform."""
|
564 |
+
if not socket.has_ipv6 or AF_INET6 is None:
|
565 |
+
return False
|
566 |
+
try:
|
567 |
+
sock = socket.socket(AF_INET6, socket.SOCK_STREAM)
|
568 |
+
with contextlib.closing(sock):
|
569 |
+
sock.bind(("::1", 0))
|
570 |
+
return True
|
571 |
+
except socket.error:
|
572 |
+
return False
|
573 |
+
|
574 |
+
|
575 |
+
def parse_environ_block(data):
|
576 |
+
"""Parse a C environ block of environment variables into a dictionary."""
|
577 |
+
# The block is usually raw data from the target process. It might contain
|
578 |
+
# trailing garbage and lines that do not look like assignments.
|
579 |
+
ret = {}
|
580 |
+
pos = 0
|
581 |
+
|
582 |
+
# localize global variable to speed up access.
|
583 |
+
WINDOWS_ = WINDOWS
|
584 |
+
while True:
|
585 |
+
next_pos = data.find("\0", pos)
|
586 |
+
# nul byte at the beginning or double nul byte means finish
|
587 |
+
if next_pos <= pos:
|
588 |
+
break
|
589 |
+
# there might not be an equals sign
|
590 |
+
equal_pos = data.find("=", pos, next_pos)
|
591 |
+
if equal_pos > pos:
|
592 |
+
key = data[pos:equal_pos]
|
593 |
+
value = data[equal_pos + 1 : next_pos]
|
594 |
+
# Windows expects environment variables to be uppercase only
|
595 |
+
if WINDOWS_:
|
596 |
+
key = key.upper()
|
597 |
+
ret[key] = value
|
598 |
+
pos = next_pos + 1
|
599 |
+
|
600 |
+
return ret
|
601 |
+
|
602 |
+
|
603 |
+
def sockfam_to_enum(num):
|
604 |
+
"""Convert a numeric socket family value to an IntEnum member.
|
605 |
+
If it's not a known member, return the numeric value itself.
|
606 |
+
"""
|
607 |
+
if enum is None:
|
608 |
+
return num
|
609 |
+
else: # pragma: no cover
|
610 |
+
try:
|
611 |
+
return socket.AddressFamily(num)
|
612 |
+
except ValueError:
|
613 |
+
return num
|
614 |
+
|
615 |
+
|
616 |
+
def socktype_to_enum(num):
|
617 |
+
"""Convert a numeric socket type value to an IntEnum member.
|
618 |
+
If it's not a known member, return the numeric value itself.
|
619 |
+
"""
|
620 |
+
if enum is None:
|
621 |
+
return num
|
622 |
+
else: # pragma: no cover
|
623 |
+
try:
|
624 |
+
return socket.SocketKind(num)
|
625 |
+
except ValueError:
|
626 |
+
return num
|
627 |
+
|
628 |
+
|
629 |
+
def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None):
|
630 |
+
"""Convert a raw connection tuple to a proper ntuple."""
|
631 |
+
if fam in (socket.AF_INET, AF_INET6):
|
632 |
+
if laddr:
|
633 |
+
laddr = addr(*laddr)
|
634 |
+
if raddr:
|
635 |
+
raddr = addr(*raddr)
|
636 |
+
if type_ == socket.SOCK_STREAM and fam in (AF_INET, AF_INET6):
|
637 |
+
status = status_map.get(status, CONN_NONE)
|
638 |
+
else:
|
639 |
+
status = CONN_NONE # ignore whatever C returned to us
|
640 |
+
fam = sockfam_to_enum(fam)
|
641 |
+
type_ = socktype_to_enum(type_)
|
642 |
+
if pid is None:
|
643 |
+
return pconn(fd, fam, type_, laddr, raddr, status)
|
644 |
+
else:
|
645 |
+
return sconn(fd, fam, type_, laddr, raddr, status, pid)
|
646 |
+
|
647 |
+
|
648 |
+
def deprecated_method(replacement):
|
649 |
+
"""A decorator which can be used to mark a method as deprecated
|
650 |
+
'replcement' is the method name which will be called instead.
|
651 |
+
"""
|
652 |
+
|
653 |
+
def outer(fun):
|
654 |
+
msg = "%s() is deprecated and will be removed; use %s() instead" % (
|
655 |
+
fun.__name__,
|
656 |
+
replacement,
|
657 |
+
)
|
658 |
+
if fun.__doc__ is None:
|
659 |
+
fun.__doc__ = msg
|
660 |
+
|
661 |
+
@functools.wraps(fun)
|
662 |
+
def inner(self, *args, **kwargs):
|
663 |
+
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
|
664 |
+
return getattr(self, replacement)(*args, **kwargs)
|
665 |
+
|
666 |
+
return inner
|
667 |
+
|
668 |
+
return outer
|
669 |
+
|
670 |
+
|
671 |
+
class _WrapNumbers:
|
672 |
+
"""Watches numbers so that they don't overflow and wrap
|
673 |
+
(reset to zero).
|
674 |
+
"""
|
675 |
+
|
676 |
+
def __init__(self):
|
677 |
+
self.lock = threading.Lock()
|
678 |
+
self.cache = {}
|
679 |
+
self.reminders = {}
|
680 |
+
self.reminder_keys = {}
|
681 |
+
|
682 |
+
def _add_dict(self, input_dict, name):
|
683 |
+
assert name not in self.cache
|
684 |
+
assert name not in self.reminders
|
685 |
+
assert name not in self.reminder_keys
|
686 |
+
self.cache[name] = input_dict
|
687 |
+
self.reminders[name] = collections.defaultdict(int)
|
688 |
+
self.reminder_keys[name] = collections.defaultdict(set)
|
689 |
+
|
690 |
+
def _remove_dead_reminders(self, input_dict, name):
|
691 |
+
"""In case the number of keys changed between calls (e.g. a
|
692 |
+
disk disappears) this removes the entry from self.reminders.
|
693 |
+
"""
|
694 |
+
old_dict = self.cache[name]
|
695 |
+
gone_keys = set(old_dict.keys()) - set(input_dict.keys())
|
696 |
+
for gone_key in gone_keys:
|
697 |
+
for remkey in self.reminder_keys[name][gone_key]:
|
698 |
+
del self.reminders[name][remkey]
|
699 |
+
del self.reminder_keys[name][gone_key]
|
700 |
+
|
701 |
+
def run(self, input_dict, name):
|
702 |
+
"""Cache dict and sum numbers which overflow and wrap.
|
703 |
+
Return an updated copy of `input_dict`.
|
704 |
+
"""
|
705 |
+
if name not in self.cache:
|
706 |
+
# This was the first call.
|
707 |
+
self._add_dict(input_dict, name)
|
708 |
+
return input_dict
|
709 |
+
|
710 |
+
self._remove_dead_reminders(input_dict, name)
|
711 |
+
|
712 |
+
old_dict = self.cache[name]
|
713 |
+
new_dict = {}
|
714 |
+
for key in input_dict:
|
715 |
+
input_tuple = input_dict[key]
|
716 |
+
try:
|
717 |
+
old_tuple = old_dict[key]
|
718 |
+
except KeyError:
|
719 |
+
# The input dict has a new key (e.g. a new disk or NIC)
|
720 |
+
# which didn't exist in the previous call.
|
721 |
+
new_dict[key] = input_tuple
|
722 |
+
continue
|
723 |
+
|
724 |
+
bits = []
|
725 |
+
for i in range(len(input_tuple)):
|
726 |
+
input_value = input_tuple[i]
|
727 |
+
old_value = old_tuple[i]
|
728 |
+
remkey = (key, i)
|
729 |
+
if input_value < old_value:
|
730 |
+
# it wrapped!
|
731 |
+
self.reminders[name][remkey] += old_value
|
732 |
+
self.reminder_keys[name][key].add(remkey)
|
733 |
+
bits.append(input_value + self.reminders[name][remkey])
|
734 |
+
|
735 |
+
new_dict[key] = tuple(bits)
|
736 |
+
|
737 |
+
self.cache[name] = input_dict
|
738 |
+
return new_dict
|
739 |
+
|
740 |
+
def cache_clear(self, name=None):
|
741 |
+
"""Clear the internal cache, optionally only for function 'name'."""
|
742 |
+
with self.lock:
|
743 |
+
if name is None:
|
744 |
+
self.cache.clear()
|
745 |
+
self.reminders.clear()
|
746 |
+
self.reminder_keys.clear()
|
747 |
+
else:
|
748 |
+
self.cache.pop(name, None)
|
749 |
+
self.reminders.pop(name, None)
|
750 |
+
self.reminder_keys.pop(name, None)
|
751 |
+
|
752 |
+
def cache_info(self):
|
753 |
+
"""Return internal cache dicts as a tuple of 3 elements."""
|
754 |
+
with self.lock:
|
755 |
+
return (self.cache, self.reminders, self.reminder_keys)
|
756 |
+
|
757 |
+
|
758 |
+
def wrap_numbers(input_dict, name):
|
759 |
+
"""Given an `input_dict` and a function `name`, adjust the numbers
|
760 |
+
which "wrap" (restart from zero) across different calls by adding
|
761 |
+
"old value" to "new value" and return an updated dict.
|
762 |
+
"""
|
763 |
+
with _wn.lock:
|
764 |
+
return _wn.run(input_dict, name)
|
765 |
+
|
766 |
+
|
767 |
+
_wn = _WrapNumbers()
|
768 |
+
wrap_numbers.cache_clear = _wn.cache_clear
|
769 |
+
wrap_numbers.cache_info = _wn.cache_info
|
770 |
+
|
771 |
+
|
772 |
+
# The read buffer size for open() builtin. This (also) dictates how
|
773 |
+
# much data we read(2) when iterating over file lines as in:
|
774 |
+
# >>> with open(file) as f:
|
775 |
+
# ... for line in f:
|
776 |
+
# ... ...
|
777 |
+
# Default per-line buffer size for binary files is 1K. For text files
|
778 |
+
# is 8K. We use a bigger buffer (32K) in order to have more consistent
|
779 |
+
# results when reading /proc pseudo files on Linux, see:
|
780 |
+
# https://github.com/giampaolo/psutil/issues/2050
|
781 |
+
# On Python 2 this also speeds up the reading of big files:
|
782 |
+
# (namely /proc/{pid}/smaps and /proc/net/*):
|
783 |
+
# https://github.com/giampaolo/psutil/issues/708
|
784 |
+
FILE_READ_BUFFER_SIZE = 32 * 1024
|
785 |
+
|
786 |
+
|
787 |
+
def open_binary(fname):
|
788 |
+
return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE)
|
789 |
+
|
790 |
+
|
791 |
+
def open_text(fname):
|
792 |
+
"""On Python 3 opens a file in text mode by using fs encoding and
|
793 |
+
a proper en/decoding errors handler.
|
794 |
+
On Python 2 this is just an alias for open(name, 'rt').
|
795 |
+
"""
|
796 |
+
if not PY3:
|
797 |
+
return open(fname, buffering=FILE_READ_BUFFER_SIZE)
|
798 |
+
|
799 |
+
# See:
|
800 |
+
# https://github.com/giampaolo/psutil/issues/675
|
801 |
+
# https://github.com/giampaolo/psutil/pull/733
|
802 |
+
fobj = open(
|
803 |
+
fname,
|
804 |
+
buffering=FILE_READ_BUFFER_SIZE,
|
805 |
+
encoding=ENCODING,
|
806 |
+
errors=ENCODING_ERRS,
|
807 |
+
)
|
808 |
+
try:
|
809 |
+
# Dictates per-line read(2) buffer size. Defaults is 8k. See:
|
810 |
+
# https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546
|
811 |
+
fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE
|
812 |
+
except AttributeError:
|
813 |
+
pass
|
814 |
+
except Exception:
|
815 |
+
fobj.close()
|
816 |
+
raise
|
817 |
+
|
818 |
+
return fobj
|
819 |
+
|
820 |
+
|
821 |
+
def cat(fname, fallback=_DEFAULT, _open=open_text):
|
822 |
+
"""Read entire file content and return it as a string. File is
|
823 |
+
opened in text mode. If specified, `fallback` is the value
|
824 |
+
returned in case of error, either if the file does not exist or
|
825 |
+
it can't be read().
|
826 |
+
"""
|
827 |
+
if fallback is _DEFAULT:
|
828 |
+
with _open(fname) as f:
|
829 |
+
return f.read()
|
830 |
+
else:
|
831 |
+
try:
|
832 |
+
with _open(fname) as f:
|
833 |
+
return f.read()
|
834 |
+
except (IOError, OSError):
|
835 |
+
return fallback
|
836 |
+
|
837 |
+
|
838 |
+
def bcat(fname, fallback=_DEFAULT):
|
839 |
+
"""Same as above but opens file in binary mode."""
|
840 |
+
return cat(fname, fallback=fallback, _open=open_binary)
|
841 |
+
|
842 |
+
|
843 |
+
def bytes2human(n, format="%(value).1f%(symbol)s"):
|
844 |
+
"""Used by various scripts. See: http://goo.gl/zeJZl.
|
845 |
+
|
846 |
+
>>> bytes2human(10000)
|
847 |
+
'9.8K'
|
848 |
+
>>> bytes2human(100001221)
|
849 |
+
'95.4M'
|
850 |
+
"""
|
851 |
+
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
|
852 |
+
prefix = {}
|
853 |
+
for i, s in enumerate(symbols[1:]):
|
854 |
+
prefix[s] = 1 << (i + 1) * 10
|
855 |
+
for symbol in reversed(symbols[1:]):
|
856 |
+
if abs(n) >= prefix[symbol]:
|
857 |
+
value = float(n) / prefix[symbol]
|
858 |
+
return format % locals()
|
859 |
+
return format % dict(symbol=symbols[0], value=n)
|
860 |
+
|
861 |
+
|
862 |
+
def get_procfs_path():
|
863 |
+
"""Return updated psutil.PROCFS_PATH constant."""
|
864 |
+
return sys.modules['psutil'].PROCFS_PATH
|
865 |
+
|
866 |
+
|
867 |
+
if PY3:
|
868 |
+
|
869 |
+
def decode(s):
|
870 |
+
return s.decode(encoding=ENCODING, errors=ENCODING_ERRS)
|
871 |
+
|
872 |
+
else:
|
873 |
+
|
874 |
+
def decode(s):
|
875 |
+
return s
|
876 |
+
|
877 |
+
|
878 |
+
# =====================================================================
|
879 |
+
# --- shell utils
|
880 |
+
# =====================================================================
|
881 |
+
|
882 |
+
|
883 |
+
@memoize
|
884 |
+
def term_supports_colors(file=sys.stdout): # pragma: no cover
|
885 |
+
if os.name == 'nt':
|
886 |
+
return True
|
887 |
+
try:
|
888 |
+
import curses
|
889 |
+
|
890 |
+
assert file.isatty()
|
891 |
+
curses.setupterm()
|
892 |
+
assert curses.tigetnum("colors") > 0
|
893 |
+
except Exception: # noqa: BLE001
|
894 |
+
return False
|
895 |
+
else:
|
896 |
+
return True
|
897 |
+
|
898 |
+
|
899 |
+
def hilite(s, color=None, bold=False): # pragma: no cover
|
900 |
+
"""Return an highlighted version of 'string'."""
|
901 |
+
if not term_supports_colors():
|
902 |
+
return s
|
903 |
+
attr = []
|
904 |
+
colors = dict(
|
905 |
+
blue='34',
|
906 |
+
brown='33',
|
907 |
+
darkgrey='30',
|
908 |
+
green='32',
|
909 |
+
grey='37',
|
910 |
+
lightblue='36',
|
911 |
+
red='91',
|
912 |
+
violet='35',
|
913 |
+
yellow='93',
|
914 |
+
)
|
915 |
+
colors[None] = '29'
|
916 |
+
try:
|
917 |
+
color = colors[color]
|
918 |
+
except KeyError:
|
919 |
+
raise ValueError(
|
920 |
+
"invalid color %r; choose between %s" % (list(colors.keys()))
|
921 |
+
)
|
922 |
+
attr.append(color)
|
923 |
+
if bold:
|
924 |
+
attr.append('1')
|
925 |
+
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
|
926 |
+
|
927 |
+
|
928 |
+
def print_color(
|
929 |
+
s, color=None, bold=False, file=sys.stdout
|
930 |
+
): # pragma: no cover
|
931 |
+
"""Print a colorized version of string."""
|
932 |
+
if not term_supports_colors():
|
933 |
+
print(s, file=file) # NOQA
|
934 |
+
elif POSIX:
|
935 |
+
print(hilite(s, color, bold), file=file) # NOQA
|
936 |
+
else:
|
937 |
+
import ctypes
|
938 |
+
|
939 |
+
DEFAULT_COLOR = 7
|
940 |
+
GetStdHandle = ctypes.windll.Kernel32.GetStdHandle
|
941 |
+
SetConsoleTextAttribute = (
|
942 |
+
ctypes.windll.Kernel32.SetConsoleTextAttribute
|
943 |
+
)
|
944 |
+
|
945 |
+
colors = dict(green=2, red=4, brown=6, yellow=6)
|
946 |
+
colors[None] = DEFAULT_COLOR
|
947 |
+
try:
|
948 |
+
color = colors[color]
|
949 |
+
except KeyError:
|
950 |
+
raise ValueError(
|
951 |
+
"invalid color %r; choose between %r"
|
952 |
+
% (color, list(colors.keys()))
|
953 |
+
)
|
954 |
+
if bold and color <= 7:
|
955 |
+
color += 8
|
956 |
+
|
957 |
+
handle_id = -12 if file is sys.stderr else -11
|
958 |
+
GetStdHandle.restype = ctypes.c_ulong
|
959 |
+
handle = GetStdHandle(handle_id)
|
960 |
+
SetConsoleTextAttribute(handle, color)
|
961 |
+
try:
|
962 |
+
print(s, file=file) # NOQA
|
963 |
+
finally:
|
964 |
+
SetConsoleTextAttribute(handle, DEFAULT_COLOR)
|
965 |
+
|
966 |
+
|
967 |
+
def debug(msg):
|
968 |
+
"""If PSUTIL_DEBUG env var is set, print a debug message to stderr."""
|
969 |
+
if PSUTIL_DEBUG:
|
970 |
+
import inspect
|
971 |
+
|
972 |
+
fname, lineno, _, lines, index = inspect.getframeinfo(
|
973 |
+
inspect.currentframe().f_back
|
974 |
+
)
|
975 |
+
if isinstance(msg, Exception):
|
976 |
+
if isinstance(msg, (OSError, IOError, EnvironmentError)):
|
977 |
+
# ...because str(exc) may contain info about the file name
|
978 |
+
msg = "ignoring %s" % msg
|
979 |
+
else:
|
980 |
+
msg = "ignoring %r" % msg
|
981 |
+
print( # noqa
|
982 |
+
"psutil-debug [%s:%s]> %s" % (fname, lineno, msg), file=sys.stderr
|
983 |
+
)
|
env-llmeval/lib/python3.10/site-packages/ps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LICENSE file.
|
4 |
+
|
5 |
+
"""Module which provides compatibility with older Python versions.
|
6 |
+
This is more future-compatible rather than the opposite (prefer latest
|
7 |
+
Python 3 way of doing things).
|
8 |
+
"""
|
9 |
+
|
10 |
+
import collections
|
11 |
+
import contextlib
|
12 |
+
import errno
|
13 |
+
import functools
|
14 |
+
import os
|
15 |
+
import sys
|
16 |
+
import types
|
17 |
+
|
18 |
+
|
19 |
+
# fmt: off
|
20 |
+
__all__ = [
|
21 |
+
# constants
|
22 |
+
"PY3",
|
23 |
+
# builtins
|
24 |
+
"long", "range", "super", "unicode", "basestring",
|
25 |
+
# literals
|
26 |
+
"u", "b",
|
27 |
+
# collections module
|
28 |
+
"lru_cache",
|
29 |
+
# shutil module
|
30 |
+
"which", "get_terminal_size",
|
31 |
+
# contextlib module
|
32 |
+
"redirect_stderr",
|
33 |
+
# python 3 exceptions
|
34 |
+
"FileNotFoundError", "PermissionError", "ProcessLookupError",
|
35 |
+
"InterruptedError", "ChildProcessError", "FileExistsError",
|
36 |
+
]
|
37 |
+
# fmt: on
|
38 |
+
|
39 |
+
|
40 |
+
PY3 = sys.version_info[0] >= 3
|
41 |
+
_SENTINEL = object()
|
42 |
+
|
43 |
+
if PY3:
|
44 |
+
long = int
|
45 |
+
xrange = range
|
46 |
+
unicode = str
|
47 |
+
basestring = str
|
48 |
+
range = range
|
49 |
+
|
50 |
+
def u(s):
|
51 |
+
return s
|
52 |
+
|
53 |
+
def b(s):
|
54 |
+
return s.encode("latin-1")
|
55 |
+
|
56 |
+
else:
|
57 |
+
long = long
|
58 |
+
range = xrange
|
59 |
+
unicode = unicode
|
60 |
+
basestring = basestring
|
61 |
+
|
62 |
+
def u(s):
|
63 |
+
return unicode(s, "unicode_escape")
|
64 |
+
|
65 |
+
def b(s):
|
66 |
+
return s
|
67 |
+
|
68 |
+
|
69 |
+
# --- builtins
|
70 |
+
|
71 |
+
|
72 |
+
# Python 3 super().
|
73 |
+
# Taken from "future" package.
|
74 |
+
# Credit: Ryan Kelly
|
75 |
+
if PY3:
|
76 |
+
super = super
|
77 |
+
else:
|
78 |
+
_builtin_super = super
|
79 |
+
|
80 |
+
def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
|
81 |
+
"""Like Python 3 builtin super(). If called without any arguments
|
82 |
+
it attempts to infer them at runtime.
|
83 |
+
"""
|
84 |
+
if type_ is _SENTINEL:
|
85 |
+
f = sys._getframe(framedepth)
|
86 |
+
try:
|
87 |
+
# Get the function's first positional argument.
|
88 |
+
type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
|
89 |
+
except (IndexError, KeyError):
|
90 |
+
msg = 'super() used in a function with no args'
|
91 |
+
raise RuntimeError(msg)
|
92 |
+
try:
|
93 |
+
# Get the MRO so we can crawl it.
|
94 |
+
mro = type_or_obj.__mro__
|
95 |
+
except (AttributeError, RuntimeError):
|
96 |
+
try:
|
97 |
+
mro = type_or_obj.__class__.__mro__
|
98 |
+
except AttributeError:
|
99 |
+
msg = 'super() used in a non-newstyle class'
|
100 |
+
raise RuntimeError(msg)
|
101 |
+
for type_ in mro:
|
102 |
+
# Find the class that owns the currently-executing method.
|
103 |
+
for meth in type_.__dict__.values():
|
104 |
+
# Drill down through any wrappers to the underlying func.
|
105 |
+
# This handles e.g. classmethod() and staticmethod().
|
106 |
+
try:
|
107 |
+
while not isinstance(meth, types.FunctionType):
|
108 |
+
if isinstance(meth, property):
|
109 |
+
# Calling __get__ on the property will invoke
|
110 |
+
# user code which might throw exceptions or
|
111 |
+
# have side effects
|
112 |
+
meth = meth.fget
|
113 |
+
else:
|
114 |
+
try:
|
115 |
+
meth = meth.__func__
|
116 |
+
except AttributeError:
|
117 |
+
meth = meth.__get__(type_or_obj, type_)
|
118 |
+
except (AttributeError, TypeError):
|
119 |
+
continue
|
120 |
+
if meth.func_code is f.f_code:
|
121 |
+
break # found
|
122 |
+
else:
|
123 |
+
# Not found. Move onto the next class in MRO.
|
124 |
+
continue
|
125 |
+
break # found
|
126 |
+
else:
|
127 |
+
msg = 'super() called outside a method'
|
128 |
+
raise RuntimeError(msg)
|
129 |
+
|
130 |
+
# Dispatch to builtin super().
|
131 |
+
if type_or_obj is not _SENTINEL:
|
132 |
+
return _builtin_super(type_, type_or_obj)
|
133 |
+
return _builtin_super(type_)
|
134 |
+
|
135 |
+
|
136 |
+
# --- exceptions
|
137 |
+
|
138 |
+
|
139 |
+
if PY3:
|
140 |
+
FileNotFoundError = FileNotFoundError # NOQA
|
141 |
+
PermissionError = PermissionError # NOQA
|
142 |
+
ProcessLookupError = ProcessLookupError # NOQA
|
143 |
+
InterruptedError = InterruptedError # NOQA
|
144 |
+
ChildProcessError = ChildProcessError # NOQA
|
145 |
+
FileExistsError = FileExistsError # NOQA
|
146 |
+
else:
|
147 |
+
# https://github.com/PythonCharmers/python-future/blob/exceptions/
|
148 |
+
# src/future/types/exceptions/pep3151.py
|
149 |
+
import platform
|
150 |
+
|
151 |
+
def _instance_checking_exception(base_exception=Exception):
|
152 |
+
def wrapped(instance_checker):
|
153 |
+
class TemporaryClass(base_exception):
|
154 |
+
def __init__(self, *args, **kwargs):
|
155 |
+
if len(args) == 1 and isinstance(args[0], TemporaryClass):
|
156 |
+
unwrap_me = args[0]
|
157 |
+
for attr in dir(unwrap_me):
|
158 |
+
if not attr.startswith('__'):
|
159 |
+
setattr(self, attr, getattr(unwrap_me, attr))
|
160 |
+
else:
|
161 |
+
super(TemporaryClass, self).__init__( # noqa
|
162 |
+
*args, **kwargs
|
163 |
+
)
|
164 |
+
|
165 |
+
class __metaclass__(type):
|
166 |
+
def __instancecheck__(cls, inst):
|
167 |
+
return instance_checker(inst)
|
168 |
+
|
169 |
+
def __subclasscheck__(cls, classinfo):
|
170 |
+
value = sys.exc_info()[1]
|
171 |
+
return isinstance(value, cls)
|
172 |
+
|
173 |
+
TemporaryClass.__name__ = instance_checker.__name__
|
174 |
+
TemporaryClass.__doc__ = instance_checker.__doc__
|
175 |
+
return TemporaryClass
|
176 |
+
|
177 |
+
return wrapped
|
178 |
+
|
179 |
+
@_instance_checking_exception(EnvironmentError)
|
180 |
+
def FileNotFoundError(inst):
|
181 |
+
return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT
|
182 |
+
|
183 |
+
@_instance_checking_exception(EnvironmentError)
|
184 |
+
def ProcessLookupError(inst):
|
185 |
+
return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH
|
186 |
+
|
187 |
+
@_instance_checking_exception(EnvironmentError)
|
188 |
+
def PermissionError(inst):
|
189 |
+
return getattr(inst, 'errno', _SENTINEL) in (errno.EACCES, errno.EPERM)
|
190 |
+
|
191 |
+
@_instance_checking_exception(EnvironmentError)
|
192 |
+
def InterruptedError(inst):
|
193 |
+
return getattr(inst, 'errno', _SENTINEL) == errno.EINTR
|
194 |
+
|
195 |
+
@_instance_checking_exception(EnvironmentError)
|
196 |
+
def ChildProcessError(inst):
|
197 |
+
return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD
|
198 |
+
|
199 |
+
@_instance_checking_exception(EnvironmentError)
|
200 |
+
def FileExistsError(inst):
|
201 |
+
return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST
|
202 |
+
|
203 |
+
if platform.python_implementation() != "CPython":
|
204 |
+
try:
|
205 |
+
raise OSError(errno.EEXIST, "perm")
|
206 |
+
except FileExistsError:
|
207 |
+
pass
|
208 |
+
except OSError:
|
209 |
+
msg = (
|
210 |
+
"broken or incompatible Python implementation, see: "
|
211 |
+
"https://github.com/giampaolo/psutil/issues/1659"
|
212 |
+
)
|
213 |
+
raise RuntimeError(msg)
|
214 |
+
|
215 |
+
|
216 |
+
# --- stdlib additions
|
217 |
+
|
218 |
+
|
219 |
+
# py 3.2 functools.lru_cache
|
220 |
+
# Taken from: http://code.activestate.com/recipes/578078
|
221 |
+
# Credit: Raymond Hettinger
|
222 |
+
try:
|
223 |
+
from functools import lru_cache
|
224 |
+
except ImportError:
|
225 |
+
try:
|
226 |
+
from threading import RLock
|
227 |
+
except ImportError:
|
228 |
+
from dummy_threading import RLock
|
229 |
+
|
230 |
+
_CacheInfo = collections.namedtuple(
|
231 |
+
"CacheInfo", ["hits", "misses", "maxsize", "currsize"]
|
232 |
+
)
|
233 |
+
|
234 |
+
class _HashedSeq(list):
|
235 |
+
__slots__ = ('hashvalue',)
|
236 |
+
|
237 |
+
def __init__(self, tup, hash=hash):
|
238 |
+
self[:] = tup
|
239 |
+
self.hashvalue = hash(tup)
|
240 |
+
|
241 |
+
def __hash__(self):
|
242 |
+
return self.hashvalue
|
243 |
+
|
244 |
+
def _make_key(
|
245 |
+
args,
|
246 |
+
kwds,
|
247 |
+
typed,
|
248 |
+
kwd_mark=(_SENTINEL,),
|
249 |
+
fasttypes=set((int, str, frozenset, type(None))), # noqa
|
250 |
+
sorted=sorted,
|
251 |
+
tuple=tuple,
|
252 |
+
type=type,
|
253 |
+
len=len,
|
254 |
+
):
|
255 |
+
key = args
|
256 |
+
if kwds:
|
257 |
+
sorted_items = sorted(kwds.items())
|
258 |
+
key += kwd_mark
|
259 |
+
for item in sorted_items:
|
260 |
+
key += item
|
261 |
+
if typed:
|
262 |
+
key += tuple(type(v) for v in args)
|
263 |
+
if kwds:
|
264 |
+
key += tuple(type(v) for k, v in sorted_items)
|
265 |
+
elif len(key) == 1 and type(key[0]) in fasttypes:
|
266 |
+
return key[0]
|
267 |
+
return _HashedSeq(key)
|
268 |
+
|
269 |
+
def lru_cache(maxsize=100, typed=False):
|
270 |
+
"""Least-recently-used cache decorator, see:
|
271 |
+
http://docs.python.org/3/library/functools.html#functools.lru_cache.
|
272 |
+
"""
|
273 |
+
|
274 |
+
def decorating_function(user_function):
|
275 |
+
cache = {}
|
276 |
+
stats = [0, 0]
|
277 |
+
HITS, MISSES = 0, 1
|
278 |
+
make_key = _make_key
|
279 |
+
cache_get = cache.get
|
280 |
+
_len = len
|
281 |
+
lock = RLock()
|
282 |
+
root = []
|
283 |
+
root[:] = [root, root, None, None]
|
284 |
+
nonlocal_root = [root]
|
285 |
+
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3
|
286 |
+
if maxsize == 0:
|
287 |
+
|
288 |
+
def wrapper(*args, **kwds):
|
289 |
+
result = user_function(*args, **kwds)
|
290 |
+
stats[MISSES] += 1
|
291 |
+
return result
|
292 |
+
|
293 |
+
elif maxsize is None:
|
294 |
+
|
295 |
+
def wrapper(*args, **kwds):
|
296 |
+
key = make_key(args, kwds, typed)
|
297 |
+
result = cache_get(key, root)
|
298 |
+
if result is not root:
|
299 |
+
stats[HITS] += 1
|
300 |
+
return result
|
301 |
+
result = user_function(*args, **kwds)
|
302 |
+
cache[key] = result
|
303 |
+
stats[MISSES] += 1
|
304 |
+
return result
|
305 |
+
|
306 |
+
else:
|
307 |
+
|
308 |
+
def wrapper(*args, **kwds):
|
309 |
+
if kwds or typed:
|
310 |
+
key = make_key(args, kwds, typed)
|
311 |
+
else:
|
312 |
+
key = args
|
313 |
+
lock.acquire()
|
314 |
+
try:
|
315 |
+
link = cache_get(key)
|
316 |
+
if link is not None:
|
317 |
+
(root,) = nonlocal_root
|
318 |
+
link_prev, link_next, key, result = link
|
319 |
+
link_prev[NEXT] = link_next
|
320 |
+
link_next[PREV] = link_prev
|
321 |
+
last = root[PREV]
|
322 |
+
last[NEXT] = root[PREV] = link
|
323 |
+
link[PREV] = last
|
324 |
+
link[NEXT] = root
|
325 |
+
stats[HITS] += 1
|
326 |
+
return result
|
327 |
+
finally:
|
328 |
+
lock.release()
|
329 |
+
result = user_function(*args, **kwds)
|
330 |
+
lock.acquire()
|
331 |
+
try:
|
332 |
+
(root,) = nonlocal_root
|
333 |
+
if key in cache:
|
334 |
+
pass
|
335 |
+
elif _len(cache) >= maxsize:
|
336 |
+
oldroot = root
|
337 |
+
oldroot[KEY] = key
|
338 |
+
oldroot[RESULT] = result
|
339 |
+
root = nonlocal_root[0] = oldroot[NEXT]
|
340 |
+
oldkey = root[KEY]
|
341 |
+
root[KEY] = root[RESULT] = None
|
342 |
+
del cache[oldkey]
|
343 |
+
cache[key] = oldroot
|
344 |
+
else:
|
345 |
+
last = root[PREV]
|
346 |
+
link = [last, root, key, result]
|
347 |
+
last[NEXT] = root[PREV] = cache[key] = link
|
348 |
+
stats[MISSES] += 1
|
349 |
+
finally:
|
350 |
+
lock.release()
|
351 |
+
return result
|
352 |
+
|
353 |
+
def cache_info():
|
354 |
+
"""Report cache statistics."""
|
355 |
+
lock.acquire()
|
356 |
+
try:
|
357 |
+
return _CacheInfo(
|
358 |
+
stats[HITS], stats[MISSES], maxsize, len(cache)
|
359 |
+
)
|
360 |
+
finally:
|
361 |
+
lock.release()
|
362 |
+
|
363 |
+
def cache_clear():
|
364 |
+
"""Clear the cache and cache statistics."""
|
365 |
+
lock.acquire()
|
366 |
+
try:
|
367 |
+
cache.clear()
|
368 |
+
root = nonlocal_root[0]
|
369 |
+
root[:] = [root, root, None, None]
|
370 |
+
stats[:] = [0, 0]
|
371 |
+
finally:
|
372 |
+
lock.release()
|
373 |
+
|
374 |
+
wrapper.__wrapped__ = user_function
|
375 |
+
wrapper.cache_info = cache_info
|
376 |
+
wrapper.cache_clear = cache_clear
|
377 |
+
return functools.update_wrapper(wrapper, user_function)
|
378 |
+
|
379 |
+
return decorating_function
|
380 |
+
|
381 |
+
|
382 |
+
# python 3.3
|
383 |
+
try:
|
384 |
+
from shutil import which
|
385 |
+
except ImportError:
|
386 |
+
|
387 |
+
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
|
388 |
+
"""Given a command, mode, and a PATH string, return the path which
|
389 |
+
conforms to the given mode on the PATH, or None if there is no such
|
390 |
+
file.
|
391 |
+
|
392 |
+
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
|
393 |
+
of os.environ.get("PATH"), or can be overridden with a custom search
|
394 |
+
path.
|
395 |
+
"""
|
396 |
+
|
397 |
+
def _access_check(fn, mode):
|
398 |
+
return (
|
399 |
+
os.path.exists(fn)
|
400 |
+
and os.access(fn, mode)
|
401 |
+
and not os.path.isdir(fn)
|
402 |
+
)
|
403 |
+
|
404 |
+
if os.path.dirname(cmd):
|
405 |
+
if _access_check(cmd, mode):
|
406 |
+
return cmd
|
407 |
+
return None
|
408 |
+
|
409 |
+
if path is None:
|
410 |
+
path = os.environ.get("PATH", os.defpath)
|
411 |
+
if not path:
|
412 |
+
return None
|
413 |
+
path = path.split(os.pathsep)
|
414 |
+
|
415 |
+
if sys.platform == "win32":
|
416 |
+
if os.curdir not in path:
|
417 |
+
path.insert(0, os.curdir)
|
418 |
+
|
419 |
+
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
|
420 |
+
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
|
421 |
+
files = [cmd]
|
422 |
+
else:
|
423 |
+
files = [cmd + ext for ext in pathext]
|
424 |
+
else:
|
425 |
+
files = [cmd]
|
426 |
+
|
427 |
+
seen = set()
|
428 |
+
for dir in path:
|
429 |
+
normdir = os.path.normcase(dir)
|
430 |
+
if normdir not in seen:
|
431 |
+
seen.add(normdir)
|
432 |
+
for thefile in files:
|
433 |
+
name = os.path.join(dir, thefile)
|
434 |
+
if _access_check(name, mode):
|
435 |
+
return name
|
436 |
+
return None
|
437 |
+
|
438 |
+
|
439 |
+
# python 3.3
|
440 |
+
try:
|
441 |
+
from shutil import get_terminal_size
|
442 |
+
except ImportError:
|
443 |
+
|
444 |
+
def get_terminal_size(fallback=(80, 24)):
|
445 |
+
try:
|
446 |
+
import fcntl
|
447 |
+
import struct
|
448 |
+
import termios
|
449 |
+
except ImportError:
|
450 |
+
return fallback
|
451 |
+
else:
|
452 |
+
try:
|
453 |
+
# This should work on Linux.
|
454 |
+
res = struct.unpack(
|
455 |
+
'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')
|
456 |
+
)
|
457 |
+
return (res[1], res[0])
|
458 |
+
except Exception: # noqa: BLE001
|
459 |
+
return fallback
|
460 |
+
|
461 |
+
|
462 |
+
# python 3.3
|
463 |
+
try:
|
464 |
+
from subprocess import TimeoutExpired as SubprocessTimeoutExpired
|
465 |
+
except ImportError:
|
466 |
+
|
467 |
+
class SubprocessTimeoutExpired(Exception):
|
468 |
+
pass
|
469 |
+
|
470 |
+
|
471 |
+
# python 3.5
|
472 |
+
try:
|
473 |
+
from contextlib import redirect_stderr
|
474 |
+
except ImportError:
|
475 |
+
|
476 |
+
@contextlib.contextmanager
|
477 |
+
def redirect_stderr(new_target):
|
478 |
+
original = sys.stderr
|
479 |
+
try:
|
480 |
+
sys.stderr = new_target
|
481 |
+
yield new_target
|
482 |
+
finally:
|
483 |
+
sys.stderr = original
|
env-llmeval/lib/python3.10/site-packages/psutil/_psaix.py
ADDED
@@ -0,0 +1,582 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'
|
2 |
+
# Copyright (c) 2017, Arnon Yaari
|
3 |
+
# All rights reserved.
|
4 |
+
# Use of this source code is governed by a BSD-style license that can be
|
5 |
+
# found in the LICENSE file.
|
6 |
+
|
7 |
+
"""AIX platform implementation."""
|
8 |
+
|
9 |
+
import functools
|
10 |
+
import glob
|
11 |
+
import os
|
12 |
+
import re
|
13 |
+
import subprocess
|
14 |
+
import sys
|
15 |
+
from collections import namedtuple
|
16 |
+
|
17 |
+
from . import _common
|
18 |
+
from . import _psposix
|
19 |
+
from . import _psutil_aix as cext
|
20 |
+
from . import _psutil_posix as cext_posix
|
21 |
+
from ._common import NIC_DUPLEX_FULL
|
22 |
+
from ._common import NIC_DUPLEX_HALF
|
23 |
+
from ._common import NIC_DUPLEX_UNKNOWN
|
24 |
+
from ._common import AccessDenied
|
25 |
+
from ._common import NoSuchProcess
|
26 |
+
from ._common import ZombieProcess
|
27 |
+
from ._common import conn_to_ntuple
|
28 |
+
from ._common import get_procfs_path
|
29 |
+
from ._common import memoize_when_activated
|
30 |
+
from ._common import usage_percent
|
31 |
+
from ._compat import PY3
|
32 |
+
from ._compat import FileNotFoundError
|
33 |
+
from ._compat import PermissionError
|
34 |
+
from ._compat import ProcessLookupError
|
35 |
+
|
36 |
+
|
37 |
+
__extra__all__ = ["PROCFS_PATH"]
|
38 |
+
|
39 |
+
|
40 |
+
# =====================================================================
|
41 |
+
# --- globals
|
42 |
+
# =====================================================================
|
43 |
+
|
44 |
+
|
45 |
+
HAS_THREADS = hasattr(cext, "proc_threads")
|
46 |
+
HAS_NET_IO_COUNTERS = hasattr(cext, "net_io_counters")
|
47 |
+
HAS_PROC_IO_COUNTERS = hasattr(cext, "proc_io_counters")
|
48 |
+
|
49 |
+
PAGE_SIZE = cext_posix.getpagesize()
|
50 |
+
AF_LINK = cext_posix.AF_LINK
|
51 |
+
|
52 |
+
PROC_STATUSES = {
|
53 |
+
cext.SIDL: _common.STATUS_IDLE,
|
54 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
55 |
+
cext.SACTIVE: _common.STATUS_RUNNING,
|
56 |
+
cext.SSWAP: _common.STATUS_RUNNING, # TODO what status is this?
|
57 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
58 |
+
}
|
59 |
+
|
60 |
+
TCP_STATUSES = {
|
61 |
+
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
62 |
+
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
63 |
+
cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
|
64 |
+
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
65 |
+
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
66 |
+
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
67 |
+
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
68 |
+
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
69 |
+
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
70 |
+
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
71 |
+
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
72 |
+
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
73 |
+
}
|
74 |
+
|
75 |
+
proc_info_map = dict(
|
76 |
+
ppid=0,
|
77 |
+
rss=1,
|
78 |
+
vms=2,
|
79 |
+
create_time=3,
|
80 |
+
nice=4,
|
81 |
+
num_threads=5,
|
82 |
+
status=6,
|
83 |
+
ttynr=7,
|
84 |
+
)
|
85 |
+
|
86 |
+
|
87 |
+
# =====================================================================
|
88 |
+
# --- named tuples
|
89 |
+
# =====================================================================
|
90 |
+
|
91 |
+
|
92 |
+
# psutil.Process.memory_info()
|
93 |
+
pmem = namedtuple('pmem', ['rss', 'vms'])
|
94 |
+
# psutil.Process.memory_full_info()
|
95 |
+
pfullmem = pmem
|
96 |
+
# psutil.Process.cpu_times()
|
97 |
+
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
|
98 |
+
# psutil.virtual_memory()
|
99 |
+
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
|
100 |
+
|
101 |
+
|
102 |
+
# =====================================================================
|
103 |
+
# --- memory
|
104 |
+
# =====================================================================
|
105 |
+
|
106 |
+
|
107 |
+
def virtual_memory():
|
108 |
+
total, avail, free, pinned, inuse = cext.virtual_mem()
|
109 |
+
percent = usage_percent((total - avail), total, round_=1)
|
110 |
+
return svmem(total, avail, percent, inuse, free)
|
111 |
+
|
112 |
+
|
113 |
+
def swap_memory():
|
114 |
+
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
|
115 |
+
total, free, sin, sout = cext.swap_mem()
|
116 |
+
used = total - free
|
117 |
+
percent = usage_percent(used, total, round_=1)
|
118 |
+
return _common.sswap(total, used, free, percent, sin, sout)
|
119 |
+
|
120 |
+
|
121 |
+
# =====================================================================
|
122 |
+
# --- CPU
|
123 |
+
# =====================================================================
|
124 |
+
|
125 |
+
|
126 |
+
def cpu_times():
|
127 |
+
"""Return system-wide CPU times as a named tuple."""
|
128 |
+
ret = cext.per_cpu_times()
|
129 |
+
return scputimes(*[sum(x) for x in zip(*ret)])
|
130 |
+
|
131 |
+
|
132 |
+
def per_cpu_times():
|
133 |
+
"""Return system per-CPU times as a list of named tuples."""
|
134 |
+
ret = cext.per_cpu_times()
|
135 |
+
return [scputimes(*x) for x in ret]
|
136 |
+
|
137 |
+
|
138 |
+
def cpu_count_logical():
|
139 |
+
"""Return the number of logical CPUs in the system."""
|
140 |
+
try:
|
141 |
+
return os.sysconf("SC_NPROCESSORS_ONLN")
|
142 |
+
except ValueError:
|
143 |
+
# mimic os.cpu_count() behavior
|
144 |
+
return None
|
145 |
+
|
146 |
+
|
147 |
+
def cpu_count_cores():
|
148 |
+
cmd = ["lsdev", "-Cc", "processor"]
|
149 |
+
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
150 |
+
stdout, stderr = p.communicate()
|
151 |
+
if PY3:
|
152 |
+
stdout, stderr = (
|
153 |
+
x.decode(sys.stdout.encoding) for x in (stdout, stderr)
|
154 |
+
)
|
155 |
+
if p.returncode != 0:
|
156 |
+
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
|
157 |
+
processors = stdout.strip().splitlines()
|
158 |
+
return len(processors) or None
|
159 |
+
|
160 |
+
|
161 |
+
def cpu_stats():
|
162 |
+
"""Return various CPU stats as a named tuple."""
|
163 |
+
ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats()
|
164 |
+
return _common.scpustats(
|
165 |
+
ctx_switches, interrupts, soft_interrupts, syscalls
|
166 |
+
)
|
167 |
+
|
168 |
+
|
169 |
+
# =====================================================================
|
170 |
+
# --- disks
|
171 |
+
# =====================================================================
|
172 |
+
|
173 |
+
|
174 |
+
disk_io_counters = cext.disk_io_counters
|
175 |
+
disk_usage = _psposix.disk_usage
|
176 |
+
|
177 |
+
|
178 |
+
def disk_partitions(all=False):
|
179 |
+
"""Return system disk partitions."""
|
180 |
+
# TODO - the filtering logic should be better checked so that
|
181 |
+
# it tries to reflect 'df' as much as possible
|
182 |
+
retlist = []
|
183 |
+
partitions = cext.disk_partitions()
|
184 |
+
for partition in partitions:
|
185 |
+
device, mountpoint, fstype, opts = partition
|
186 |
+
if device == 'none':
|
187 |
+
device = ''
|
188 |
+
if not all:
|
189 |
+
# Differently from, say, Linux, we don't have a list of
|
190 |
+
# common fs types so the best we can do, AFAIK, is to
|
191 |
+
# filter by filesystem having a total size > 0.
|
192 |
+
if not disk_usage(mountpoint).total:
|
193 |
+
continue
|
194 |
+
maxfile = maxpath = None # set later
|
195 |
+
ntuple = _common.sdiskpart(
|
196 |
+
device, mountpoint, fstype, opts, maxfile, maxpath
|
197 |
+
)
|
198 |
+
retlist.append(ntuple)
|
199 |
+
return retlist
|
200 |
+
|
201 |
+
|
202 |
+
# =====================================================================
|
203 |
+
# --- network
|
204 |
+
# =====================================================================
|
205 |
+
|
206 |
+
|
207 |
+
net_if_addrs = cext_posix.net_if_addrs
|
208 |
+
|
209 |
+
if HAS_NET_IO_COUNTERS:
|
210 |
+
net_io_counters = cext.net_io_counters
|
211 |
+
|
212 |
+
|
213 |
+
def net_connections(kind, _pid=-1):
|
214 |
+
"""Return socket connections. If pid == -1 return system-wide
|
215 |
+
connections (as opposed to connections opened by one process only).
|
216 |
+
"""
|
217 |
+
cmap = _common.conn_tmap
|
218 |
+
if kind not in cmap:
|
219 |
+
raise ValueError(
|
220 |
+
"invalid %r kind argument; choose between %s"
|
221 |
+
% (kind, ', '.join([repr(x) for x in cmap]))
|
222 |
+
)
|
223 |
+
families, types = _common.conn_tmap[kind]
|
224 |
+
rawlist = cext.net_connections(_pid)
|
225 |
+
ret = []
|
226 |
+
for item in rawlist:
|
227 |
+
fd, fam, type_, laddr, raddr, status, pid = item
|
228 |
+
if fam not in families:
|
229 |
+
continue
|
230 |
+
if type_ not in types:
|
231 |
+
continue
|
232 |
+
nt = conn_to_ntuple(
|
233 |
+
fd,
|
234 |
+
fam,
|
235 |
+
type_,
|
236 |
+
laddr,
|
237 |
+
raddr,
|
238 |
+
status,
|
239 |
+
TCP_STATUSES,
|
240 |
+
pid=pid if _pid == -1 else None,
|
241 |
+
)
|
242 |
+
ret.append(nt)
|
243 |
+
return ret
|
244 |
+
|
245 |
+
|
246 |
+
def net_if_stats():
|
247 |
+
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
248 |
+
duplex_map = {"Full": NIC_DUPLEX_FULL, "Half": NIC_DUPLEX_HALF}
|
249 |
+
names = set([x[0] for x in net_if_addrs()])
|
250 |
+
ret = {}
|
251 |
+
for name in names:
|
252 |
+
mtu = cext_posix.net_if_mtu(name)
|
253 |
+
flags = cext_posix.net_if_flags(name)
|
254 |
+
|
255 |
+
# try to get speed and duplex
|
256 |
+
# TODO: rewrite this in C (entstat forks, so use truss -f to follow.
|
257 |
+
# looks like it is using an undocumented ioctl?)
|
258 |
+
duplex = ""
|
259 |
+
speed = 0
|
260 |
+
p = subprocess.Popen(
|
261 |
+
["/usr/bin/entstat", "-d", name],
|
262 |
+
stdout=subprocess.PIPE,
|
263 |
+
stderr=subprocess.PIPE,
|
264 |
+
)
|
265 |
+
stdout, stderr = p.communicate()
|
266 |
+
if PY3:
|
267 |
+
stdout, stderr = (
|
268 |
+
x.decode(sys.stdout.encoding) for x in (stdout, stderr)
|
269 |
+
)
|
270 |
+
if p.returncode == 0:
|
271 |
+
re_result = re.search(
|
272 |
+
r"Running: (\d+) Mbps.*?(\w+) Duplex", stdout
|
273 |
+
)
|
274 |
+
if re_result is not None:
|
275 |
+
speed = int(re_result.group(1))
|
276 |
+
duplex = re_result.group(2)
|
277 |
+
|
278 |
+
output_flags = ','.join(flags)
|
279 |
+
isup = 'running' in flags
|
280 |
+
duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN)
|
281 |
+
ret[name] = _common.snicstats(isup, duplex, speed, mtu, output_flags)
|
282 |
+
return ret
|
283 |
+
|
284 |
+
|
285 |
+
# =====================================================================
|
286 |
+
# --- other system functions
|
287 |
+
# =====================================================================
|
288 |
+
|
289 |
+
|
290 |
+
def boot_time():
|
291 |
+
"""The system boot time expressed in seconds since the epoch."""
|
292 |
+
return cext.boot_time()
|
293 |
+
|
294 |
+
|
295 |
+
def users():
|
296 |
+
"""Return currently connected users as a list of namedtuples."""
|
297 |
+
retlist = []
|
298 |
+
rawlist = cext.users()
|
299 |
+
localhost = (':0.0', ':0')
|
300 |
+
for item in rawlist:
|
301 |
+
user, tty, hostname, tstamp, user_process, pid = item
|
302 |
+
# note: the underlying C function includes entries about
|
303 |
+
# system boot, run level and others. We might want
|
304 |
+
# to use them in the future.
|
305 |
+
if not user_process:
|
306 |
+
continue
|
307 |
+
if hostname in localhost:
|
308 |
+
hostname = 'localhost'
|
309 |
+
nt = _common.suser(user, tty, hostname, tstamp, pid)
|
310 |
+
retlist.append(nt)
|
311 |
+
return retlist
|
312 |
+
|
313 |
+
|
314 |
+
# =====================================================================
|
315 |
+
# --- processes
|
316 |
+
# =====================================================================
|
317 |
+
|
318 |
+
|
319 |
+
def pids():
|
320 |
+
"""Returns a list of PIDs currently running on the system."""
|
321 |
+
return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
|
322 |
+
|
323 |
+
|
324 |
+
def pid_exists(pid):
|
325 |
+
"""Check for the existence of a unix pid."""
|
326 |
+
return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo"))
|
327 |
+
|
328 |
+
|
329 |
+
def wrap_exceptions(fun):
|
330 |
+
"""Call callable into a try/except clause and translate ENOENT,
|
331 |
+
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
|
332 |
+
"""
|
333 |
+
|
334 |
+
@functools.wraps(fun)
|
335 |
+
def wrapper(self, *args, **kwargs):
|
336 |
+
try:
|
337 |
+
return fun(self, *args, **kwargs)
|
338 |
+
except (FileNotFoundError, ProcessLookupError):
|
339 |
+
# ENOENT (no such file or directory) gets raised on open().
|
340 |
+
# ESRCH (no such process) can get raised on read() if
|
341 |
+
# process is gone in meantime.
|
342 |
+
if not pid_exists(self.pid):
|
343 |
+
raise NoSuchProcess(self.pid, self._name)
|
344 |
+
else:
|
345 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
346 |
+
except PermissionError:
|
347 |
+
raise AccessDenied(self.pid, self._name)
|
348 |
+
|
349 |
+
return wrapper
|
350 |
+
|
351 |
+
|
352 |
+
class Process:
|
353 |
+
"""Wrapper class around underlying C implementation."""
|
354 |
+
|
355 |
+
__slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
|
356 |
+
|
357 |
+
def __init__(self, pid):
|
358 |
+
self.pid = pid
|
359 |
+
self._name = None
|
360 |
+
self._ppid = None
|
361 |
+
self._procfs_path = get_procfs_path()
|
362 |
+
|
363 |
+
def oneshot_enter(self):
|
364 |
+
self._proc_basic_info.cache_activate(self)
|
365 |
+
self._proc_cred.cache_activate(self)
|
366 |
+
|
367 |
+
def oneshot_exit(self):
|
368 |
+
self._proc_basic_info.cache_deactivate(self)
|
369 |
+
self._proc_cred.cache_deactivate(self)
|
370 |
+
|
371 |
+
@wrap_exceptions
|
372 |
+
@memoize_when_activated
|
373 |
+
def _proc_basic_info(self):
|
374 |
+
return cext.proc_basic_info(self.pid, self._procfs_path)
|
375 |
+
|
376 |
+
@wrap_exceptions
|
377 |
+
@memoize_when_activated
|
378 |
+
def _proc_cred(self):
|
379 |
+
return cext.proc_cred(self.pid, self._procfs_path)
|
380 |
+
|
381 |
+
@wrap_exceptions
|
382 |
+
def name(self):
|
383 |
+
if self.pid == 0:
|
384 |
+
return "swapper"
|
385 |
+
# note: max 16 characters
|
386 |
+
return cext.proc_name(self.pid, self._procfs_path).rstrip("\x00")
|
387 |
+
|
388 |
+
@wrap_exceptions
|
389 |
+
def exe(self):
|
390 |
+
# there is no way to get executable path in AIX other than to guess,
|
391 |
+
# and guessing is more complex than what's in the wrapping class
|
392 |
+
cmdline = self.cmdline()
|
393 |
+
if not cmdline:
|
394 |
+
return ''
|
395 |
+
exe = cmdline[0]
|
396 |
+
if os.path.sep in exe:
|
397 |
+
# relative or absolute path
|
398 |
+
if not os.path.isabs(exe):
|
399 |
+
# if cwd has changed, we're out of luck - this may be wrong!
|
400 |
+
exe = os.path.abspath(os.path.join(self.cwd(), exe))
|
401 |
+
if (
|
402 |
+
os.path.isabs(exe)
|
403 |
+
and os.path.isfile(exe)
|
404 |
+
and os.access(exe, os.X_OK)
|
405 |
+
):
|
406 |
+
return exe
|
407 |
+
# not found, move to search in PATH using basename only
|
408 |
+
exe = os.path.basename(exe)
|
409 |
+
# search for exe name PATH
|
410 |
+
for path in os.environ["PATH"].split(":"):
|
411 |
+
possible_exe = os.path.abspath(os.path.join(path, exe))
|
412 |
+
if os.path.isfile(possible_exe) and os.access(
|
413 |
+
possible_exe, os.X_OK
|
414 |
+
):
|
415 |
+
return possible_exe
|
416 |
+
return ''
|
417 |
+
|
418 |
+
@wrap_exceptions
|
419 |
+
def cmdline(self):
|
420 |
+
return cext.proc_args(self.pid)
|
421 |
+
|
422 |
+
@wrap_exceptions
|
423 |
+
def environ(self):
|
424 |
+
return cext.proc_environ(self.pid)
|
425 |
+
|
426 |
+
@wrap_exceptions
|
427 |
+
def create_time(self):
|
428 |
+
return self._proc_basic_info()[proc_info_map['create_time']]
|
429 |
+
|
430 |
+
@wrap_exceptions
|
431 |
+
def num_threads(self):
|
432 |
+
return self._proc_basic_info()[proc_info_map['num_threads']]
|
433 |
+
|
434 |
+
if HAS_THREADS:
|
435 |
+
|
436 |
+
@wrap_exceptions
|
437 |
+
def threads(self):
|
438 |
+
rawlist = cext.proc_threads(self.pid)
|
439 |
+
retlist = []
|
440 |
+
for thread_id, utime, stime in rawlist:
|
441 |
+
ntuple = _common.pthread(thread_id, utime, stime)
|
442 |
+
retlist.append(ntuple)
|
443 |
+
# The underlying C implementation retrieves all OS threads
|
444 |
+
# and filters them by PID. At this point we can't tell whether
|
445 |
+
# an empty list means there were no connections for process or
|
446 |
+
# process is no longer active so we force NSP in case the PID
|
447 |
+
# is no longer there.
|
448 |
+
if not retlist:
|
449 |
+
# will raise NSP if process is gone
|
450 |
+
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
451 |
+
return retlist
|
452 |
+
|
453 |
+
@wrap_exceptions
|
454 |
+
def connections(self, kind='inet'):
|
455 |
+
ret = net_connections(kind, _pid=self.pid)
|
456 |
+
# The underlying C implementation retrieves all OS connections
|
457 |
+
# and filters them by PID. At this point we can't tell whether
|
458 |
+
# an empty list means there were no connections for process or
|
459 |
+
# process is no longer active so we force NSP in case the PID
|
460 |
+
# is no longer there.
|
461 |
+
if not ret:
|
462 |
+
# will raise NSP if process is gone
|
463 |
+
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
464 |
+
return ret
|
465 |
+
|
466 |
+
@wrap_exceptions
|
467 |
+
def nice_get(self):
|
468 |
+
return cext_posix.getpriority(self.pid)
|
469 |
+
|
470 |
+
@wrap_exceptions
|
471 |
+
def nice_set(self, value):
|
472 |
+
return cext_posix.setpriority(self.pid, value)
|
473 |
+
|
474 |
+
@wrap_exceptions
|
475 |
+
def ppid(self):
|
476 |
+
self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
|
477 |
+
return self._ppid
|
478 |
+
|
479 |
+
@wrap_exceptions
|
480 |
+
def uids(self):
|
481 |
+
real, effective, saved, _, _, _ = self._proc_cred()
|
482 |
+
return _common.puids(real, effective, saved)
|
483 |
+
|
484 |
+
@wrap_exceptions
|
485 |
+
def gids(self):
|
486 |
+
_, _, _, real, effective, saved = self._proc_cred()
|
487 |
+
return _common.puids(real, effective, saved)
|
488 |
+
|
489 |
+
@wrap_exceptions
|
490 |
+
def cpu_times(self):
|
491 |
+
t = cext.proc_cpu_times(self.pid, self._procfs_path)
|
492 |
+
return _common.pcputimes(*t)
|
493 |
+
|
494 |
+
@wrap_exceptions
|
495 |
+
def terminal(self):
|
496 |
+
ttydev = self._proc_basic_info()[proc_info_map['ttynr']]
|
497 |
+
# convert from 64-bit dev_t to 32-bit dev_t and then map the device
|
498 |
+
ttydev = ((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF)
|
499 |
+
# try to match rdev of /dev/pts/* files ttydev
|
500 |
+
for dev in glob.glob("/dev/**/*"):
|
501 |
+
if os.stat(dev).st_rdev == ttydev:
|
502 |
+
return dev
|
503 |
+
return None
|
504 |
+
|
505 |
+
@wrap_exceptions
|
506 |
+
def cwd(self):
|
507 |
+
procfs_path = self._procfs_path
|
508 |
+
try:
|
509 |
+
result = os.readlink("%s/%s/cwd" % (procfs_path, self.pid))
|
510 |
+
return result.rstrip('/')
|
511 |
+
except FileNotFoundError:
|
512 |
+
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
|
513 |
+
return ""
|
514 |
+
|
515 |
+
@wrap_exceptions
|
516 |
+
def memory_info(self):
|
517 |
+
ret = self._proc_basic_info()
|
518 |
+
rss = ret[proc_info_map['rss']] * 1024
|
519 |
+
vms = ret[proc_info_map['vms']] * 1024
|
520 |
+
return pmem(rss, vms)
|
521 |
+
|
522 |
+
memory_full_info = memory_info
|
523 |
+
|
524 |
+
@wrap_exceptions
|
525 |
+
def status(self):
|
526 |
+
code = self._proc_basic_info()[proc_info_map['status']]
|
527 |
+
# XXX is '?' legit? (we're not supposed to return it anyway)
|
528 |
+
return PROC_STATUSES.get(code, '?')
|
529 |
+
|
530 |
+
def open_files(self):
|
531 |
+
# TODO rewrite without using procfiles (stat /proc/pid/fd/* and then
|
532 |
+
# find matching name of the inode)
|
533 |
+
p = subprocess.Popen(
|
534 |
+
["/usr/bin/procfiles", "-n", str(self.pid)],
|
535 |
+
stdout=subprocess.PIPE,
|
536 |
+
stderr=subprocess.PIPE,
|
537 |
+
)
|
538 |
+
stdout, stderr = p.communicate()
|
539 |
+
if PY3:
|
540 |
+
stdout, stderr = (
|
541 |
+
x.decode(sys.stdout.encoding) for x in (stdout, stderr)
|
542 |
+
)
|
543 |
+
if "no such process" in stderr.lower():
|
544 |
+
raise NoSuchProcess(self.pid, self._name)
|
545 |
+
procfiles = re.findall(r"(\d+): S_IFREG.*\s*.*name:(.*)\n", stdout)
|
546 |
+
retlist = []
|
547 |
+
for fd, path in procfiles:
|
548 |
+
path = path.strip()
|
549 |
+
if path.startswith("//"):
|
550 |
+
path = path[1:]
|
551 |
+
if path.lower() == "cannot be retrieved":
|
552 |
+
continue
|
553 |
+
retlist.append(_common.popenfile(path, int(fd)))
|
554 |
+
return retlist
|
555 |
+
|
556 |
+
@wrap_exceptions
|
557 |
+
def num_fds(self):
|
558 |
+
if self.pid == 0: # no /proc/0/fd
|
559 |
+
return 0
|
560 |
+
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
|
561 |
+
|
562 |
+
@wrap_exceptions
|
563 |
+
def num_ctx_switches(self):
|
564 |
+
return _common.pctxsw(*cext.proc_num_ctx_switches(self.pid))
|
565 |
+
|
566 |
+
@wrap_exceptions
|
567 |
+
def wait(self, timeout=None):
|
568 |
+
return _psposix.wait_pid(self.pid, timeout, self._name)
|
569 |
+
|
570 |
+
if HAS_PROC_IO_COUNTERS:
|
571 |
+
|
572 |
+
@wrap_exceptions
|
573 |
+
def io_counters(self):
|
574 |
+
try:
|
575 |
+
rc, wc, rb, wb = cext.proc_io_counters(self.pid)
|
576 |
+
except OSError:
|
577 |
+
# if process is terminated, proc_io_counters returns OSError
|
578 |
+
# instead of NSP
|
579 |
+
if not pid_exists(self.pid):
|
580 |
+
raise NoSuchProcess(self.pid, self._name)
|
581 |
+
raise
|
582 |
+
return _common.pio(rc, wc, rb, wb)
|
env-llmeval/lib/python3.10/site-packages/psutil/_psbsd.py
ADDED
@@ -0,0 +1,977 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""FreeBSD, OpenBSD and NetBSD platforms implementation."""
|
6 |
+
|
7 |
+
import contextlib
|
8 |
+
import errno
|
9 |
+
import functools
|
10 |
+
import os
|
11 |
+
from collections import defaultdict
|
12 |
+
from collections import namedtuple
|
13 |
+
from xml.etree import ElementTree
|
14 |
+
|
15 |
+
from . import _common
|
16 |
+
from . import _psposix
|
17 |
+
from . import _psutil_bsd as cext
|
18 |
+
from . import _psutil_posix as cext_posix
|
19 |
+
from ._common import FREEBSD
|
20 |
+
from ._common import NETBSD
|
21 |
+
from ._common import OPENBSD
|
22 |
+
from ._common import AccessDenied
|
23 |
+
from ._common import NoSuchProcess
|
24 |
+
from ._common import ZombieProcess
|
25 |
+
from ._common import conn_tmap
|
26 |
+
from ._common import conn_to_ntuple
|
27 |
+
from ._common import debug
|
28 |
+
from ._common import memoize
|
29 |
+
from ._common import memoize_when_activated
|
30 |
+
from ._common import usage_percent
|
31 |
+
from ._compat import FileNotFoundError
|
32 |
+
from ._compat import PermissionError
|
33 |
+
from ._compat import ProcessLookupError
|
34 |
+
from ._compat import which
|
35 |
+
|
36 |
+
|
37 |
+
__extra__all__ = []
|
38 |
+
|
39 |
+
|
40 |
+
# =====================================================================
|
41 |
+
# --- globals
|
42 |
+
# =====================================================================
|
43 |
+
|
44 |
+
|
45 |
+
if FREEBSD:
|
46 |
+
PROC_STATUSES = {
|
47 |
+
cext.SIDL: _common.STATUS_IDLE,
|
48 |
+
cext.SRUN: _common.STATUS_RUNNING,
|
49 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
50 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
51 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
52 |
+
cext.SWAIT: _common.STATUS_WAITING,
|
53 |
+
cext.SLOCK: _common.STATUS_LOCKED,
|
54 |
+
}
|
55 |
+
elif OPENBSD:
|
56 |
+
PROC_STATUSES = {
|
57 |
+
cext.SIDL: _common.STATUS_IDLE,
|
58 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
59 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
60 |
+
# According to /usr/include/sys/proc.h SZOMB is unused.
|
61 |
+
# test_zombie_process() shows that SDEAD is the right
|
62 |
+
# equivalent. Also it appears there's no equivalent of
|
63 |
+
# psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE.
|
64 |
+
# cext.SZOMB: _common.STATUS_ZOMBIE,
|
65 |
+
cext.SDEAD: _common.STATUS_ZOMBIE,
|
66 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
67 |
+
# From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt
|
68 |
+
# OpenBSD has SRUN and SONPROC: SRUN indicates that a process
|
69 |
+
# is runnable but *not* yet running, i.e. is on a run queue.
|
70 |
+
# SONPROC indicates that the process is actually executing on
|
71 |
+
# a CPU, i.e. it is no longer on a run queue.
|
72 |
+
# As such we'll map SRUN to STATUS_WAKING and SONPROC to
|
73 |
+
# STATUS_RUNNING
|
74 |
+
cext.SRUN: _common.STATUS_WAKING,
|
75 |
+
cext.SONPROC: _common.STATUS_RUNNING,
|
76 |
+
}
|
77 |
+
elif NETBSD:
|
78 |
+
PROC_STATUSES = {
|
79 |
+
cext.SIDL: _common.STATUS_IDLE,
|
80 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
81 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
82 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
83 |
+
cext.SRUN: _common.STATUS_WAKING,
|
84 |
+
cext.SONPROC: _common.STATUS_RUNNING,
|
85 |
+
}
|
86 |
+
|
87 |
+
TCP_STATUSES = {
|
88 |
+
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
89 |
+
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
90 |
+
cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
|
91 |
+
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
92 |
+
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
93 |
+
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
94 |
+
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
95 |
+
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
96 |
+
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
97 |
+
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
98 |
+
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
99 |
+
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
100 |
+
}
|
101 |
+
|
102 |
+
PAGESIZE = cext_posix.getpagesize()
|
103 |
+
AF_LINK = cext_posix.AF_LINK
|
104 |
+
|
105 |
+
HAS_PER_CPU_TIMES = hasattr(cext, "per_cpu_times")
|
106 |
+
HAS_PROC_NUM_THREADS = hasattr(cext, "proc_num_threads")
|
107 |
+
HAS_PROC_OPEN_FILES = hasattr(cext, 'proc_open_files')
|
108 |
+
HAS_PROC_NUM_FDS = hasattr(cext, 'proc_num_fds')
|
109 |
+
|
110 |
+
kinfo_proc_map = dict(
|
111 |
+
ppid=0,
|
112 |
+
status=1,
|
113 |
+
real_uid=2,
|
114 |
+
effective_uid=3,
|
115 |
+
saved_uid=4,
|
116 |
+
real_gid=5,
|
117 |
+
effective_gid=6,
|
118 |
+
saved_gid=7,
|
119 |
+
ttynr=8,
|
120 |
+
create_time=9,
|
121 |
+
ctx_switches_vol=10,
|
122 |
+
ctx_switches_unvol=11,
|
123 |
+
read_io_count=12,
|
124 |
+
write_io_count=13,
|
125 |
+
user_time=14,
|
126 |
+
sys_time=15,
|
127 |
+
ch_user_time=16,
|
128 |
+
ch_sys_time=17,
|
129 |
+
rss=18,
|
130 |
+
vms=19,
|
131 |
+
memtext=20,
|
132 |
+
memdata=21,
|
133 |
+
memstack=22,
|
134 |
+
cpunum=23,
|
135 |
+
name=24,
|
136 |
+
)
|
137 |
+
|
138 |
+
|
139 |
+
# =====================================================================
|
140 |
+
# --- named tuples
|
141 |
+
# =====================================================================
|
142 |
+
|
143 |
+
|
144 |
+
# fmt: off
|
145 |
+
# psutil.virtual_memory()
|
146 |
+
svmem = namedtuple(
|
147 |
+
'svmem', ['total', 'available', 'percent', 'used', 'free',
|
148 |
+
'active', 'inactive', 'buffers', 'cached', 'shared', 'wired'])
|
149 |
+
# psutil.cpu_times()
|
150 |
+
scputimes = namedtuple(
|
151 |
+
'scputimes', ['user', 'nice', 'system', 'idle', 'irq'])
|
152 |
+
# psutil.Process.memory_info()
|
153 |
+
pmem = namedtuple('pmem', ['rss', 'vms', 'text', 'data', 'stack'])
|
154 |
+
# psutil.Process.memory_full_info()
|
155 |
+
pfullmem = pmem
|
156 |
+
# psutil.Process.cpu_times()
|
157 |
+
pcputimes = namedtuple('pcputimes',
|
158 |
+
['user', 'system', 'children_user', 'children_system'])
|
159 |
+
# psutil.Process.memory_maps(grouped=True)
|
160 |
+
pmmap_grouped = namedtuple(
|
161 |
+
'pmmap_grouped', 'path rss, private, ref_count, shadow_count')
|
162 |
+
# psutil.Process.memory_maps(grouped=False)
|
163 |
+
pmmap_ext = namedtuple(
|
164 |
+
'pmmap_ext', 'addr, perms path rss, private, ref_count, shadow_count')
|
165 |
+
# psutil.disk_io_counters()
|
166 |
+
if FREEBSD:
|
167 |
+
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
168 |
+
'read_bytes', 'write_bytes',
|
169 |
+
'read_time', 'write_time',
|
170 |
+
'busy_time'])
|
171 |
+
else:
|
172 |
+
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
173 |
+
'read_bytes', 'write_bytes'])
|
174 |
+
# fmt: on
|
175 |
+
|
176 |
+
|
177 |
+
# =====================================================================
|
178 |
+
# --- memory
|
179 |
+
# =====================================================================
|
180 |
+
|
181 |
+
|
182 |
+
def virtual_memory():
|
183 |
+
mem = cext.virtual_mem()
|
184 |
+
if NETBSD:
|
185 |
+
total, free, active, inactive, wired, cached = mem
|
186 |
+
# On NetBSD buffers and shared mem is determined via /proc.
|
187 |
+
# The C ext set them to 0.
|
188 |
+
with open('/proc/meminfo', 'rb') as f:
|
189 |
+
for line in f:
|
190 |
+
if line.startswith(b'Buffers:'):
|
191 |
+
buffers = int(line.split()[1]) * 1024
|
192 |
+
elif line.startswith(b'MemShared:'):
|
193 |
+
shared = int(line.split()[1]) * 1024
|
194 |
+
# Before avail was calculated as (inactive + cached + free),
|
195 |
+
# same as zabbix, but it turned out it could exceed total (see
|
196 |
+
# #2233), so zabbix seems to be wrong. Htop calculates it
|
197 |
+
# differently, and the used value seem more realistic, so let's
|
198 |
+
# match htop.
|
199 |
+
# https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162 # noqa
|
200 |
+
# https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135 # noqa
|
201 |
+
used = active + wired
|
202 |
+
avail = total - used
|
203 |
+
else:
|
204 |
+
total, free, active, inactive, wired, cached, buffers, shared = mem
|
205 |
+
# matches freebsd-memory CLI:
|
206 |
+
# * https://people.freebsd.org/~rse/dist/freebsd-memory
|
207 |
+
# * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt
|
208 |
+
# matches zabbix:
|
209 |
+
# * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143 # noqa
|
210 |
+
avail = inactive + cached + free
|
211 |
+
used = active + wired + cached
|
212 |
+
|
213 |
+
percent = usage_percent((total - avail), total, round_=1)
|
214 |
+
return svmem(
|
215 |
+
total,
|
216 |
+
avail,
|
217 |
+
percent,
|
218 |
+
used,
|
219 |
+
free,
|
220 |
+
active,
|
221 |
+
inactive,
|
222 |
+
buffers,
|
223 |
+
cached,
|
224 |
+
shared,
|
225 |
+
wired,
|
226 |
+
)
|
227 |
+
|
228 |
+
|
229 |
+
def swap_memory():
|
230 |
+
"""System swap memory as (total, used, free, sin, sout) namedtuple."""
|
231 |
+
total, used, free, sin, sout = cext.swap_mem()
|
232 |
+
percent = usage_percent(used, total, round_=1)
|
233 |
+
return _common.sswap(total, used, free, percent, sin, sout)
|
234 |
+
|
235 |
+
|
236 |
+
# =====================================================================
|
237 |
+
# --- CPU
|
238 |
+
# =====================================================================
|
239 |
+
|
240 |
+
|
241 |
+
def cpu_times():
|
242 |
+
"""Return system per-CPU times as a namedtuple."""
|
243 |
+
user, nice, system, idle, irq = cext.cpu_times()
|
244 |
+
return scputimes(user, nice, system, idle, irq)
|
245 |
+
|
246 |
+
|
247 |
+
if HAS_PER_CPU_TIMES:
|
248 |
+
|
249 |
+
def per_cpu_times():
|
250 |
+
"""Return system CPU times as a namedtuple."""
|
251 |
+
ret = []
|
252 |
+
for cpu_t in cext.per_cpu_times():
|
253 |
+
user, nice, system, idle, irq = cpu_t
|
254 |
+
item = scputimes(user, nice, system, idle, irq)
|
255 |
+
ret.append(item)
|
256 |
+
return ret
|
257 |
+
|
258 |
+
else:
|
259 |
+
# XXX
|
260 |
+
# Ok, this is very dirty.
|
261 |
+
# On FreeBSD < 8 we cannot gather per-cpu information, see:
|
262 |
+
# https://github.com/giampaolo/psutil/issues/226
|
263 |
+
# If num cpus > 1, on first call we return single cpu times to avoid a
|
264 |
+
# crash at psutil import time.
|
265 |
+
# Next calls will fail with NotImplementedError
|
266 |
+
def per_cpu_times():
|
267 |
+
"""Return system CPU times as a namedtuple."""
|
268 |
+
if cpu_count_logical() == 1:
|
269 |
+
return [cpu_times()]
|
270 |
+
if per_cpu_times.__called__:
|
271 |
+
msg = "supported only starting from FreeBSD 8"
|
272 |
+
raise NotImplementedError(msg)
|
273 |
+
per_cpu_times.__called__ = True
|
274 |
+
return [cpu_times()]
|
275 |
+
|
276 |
+
per_cpu_times.__called__ = False
|
277 |
+
|
278 |
+
|
279 |
+
def cpu_count_logical():
|
280 |
+
"""Return the number of logical CPUs in the system."""
|
281 |
+
return cext.cpu_count_logical()
|
282 |
+
|
283 |
+
|
284 |
+
if OPENBSD or NETBSD:
|
285 |
+
|
286 |
+
def cpu_count_cores():
|
287 |
+
# OpenBSD and NetBSD do not implement this.
|
288 |
+
return 1 if cpu_count_logical() == 1 else None
|
289 |
+
|
290 |
+
else:
|
291 |
+
|
292 |
+
def cpu_count_cores():
|
293 |
+
"""Return the number of CPU cores in the system."""
|
294 |
+
# From the C module we'll get an XML string similar to this:
|
295 |
+
# http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html
|
296 |
+
# We may get None in case "sysctl kern.sched.topology_spec"
|
297 |
+
# is not supported on this BSD version, in which case we'll mimic
|
298 |
+
# os.cpu_count() and return None.
|
299 |
+
ret = None
|
300 |
+
s = cext.cpu_topology()
|
301 |
+
if s is not None:
|
302 |
+
# get rid of padding chars appended at the end of the string
|
303 |
+
index = s.rfind("</groups>")
|
304 |
+
if index != -1:
|
305 |
+
s = s[: index + 9]
|
306 |
+
root = ElementTree.fromstring(s)
|
307 |
+
try:
|
308 |
+
ret = len(root.findall('group/children/group/cpu')) or None
|
309 |
+
finally:
|
310 |
+
# needed otherwise it will memleak
|
311 |
+
root.clear()
|
312 |
+
if not ret:
|
313 |
+
# If logical CPUs == 1 it's obvious we' have only 1 core.
|
314 |
+
if cpu_count_logical() == 1:
|
315 |
+
return 1
|
316 |
+
return ret
|
317 |
+
|
318 |
+
|
319 |
+
def cpu_stats():
|
320 |
+
"""Return various CPU stats as a named tuple."""
|
321 |
+
if FREEBSD:
|
322 |
+
# Note: the C ext is returning some metrics we are not exposing:
|
323 |
+
# traps.
|
324 |
+
ctxsw, intrs, soft_intrs, syscalls, traps = cext.cpu_stats()
|
325 |
+
elif NETBSD:
|
326 |
+
# XXX
|
327 |
+
# Note about intrs: the C extension returns 0. intrs
|
328 |
+
# can be determined via /proc/stat; it has the same value as
|
329 |
+
# soft_intrs thought so the kernel is faking it (?).
|
330 |
+
#
|
331 |
+
# Note about syscalls: the C extension always sets it to 0 (?).
|
332 |
+
#
|
333 |
+
# Note: the C ext is returning some metrics we are not exposing:
|
334 |
+
# traps, faults and forks.
|
335 |
+
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = (
|
336 |
+
cext.cpu_stats()
|
337 |
+
)
|
338 |
+
with open('/proc/stat', 'rb') as f:
|
339 |
+
for line in f:
|
340 |
+
if line.startswith(b'intr'):
|
341 |
+
intrs = int(line.split()[1])
|
342 |
+
elif OPENBSD:
|
343 |
+
# Note: the C ext is returning some metrics we are not exposing:
|
344 |
+
# traps, faults and forks.
|
345 |
+
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = (
|
346 |
+
cext.cpu_stats()
|
347 |
+
)
|
348 |
+
return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls)
|
349 |
+
|
350 |
+
|
351 |
+
if FREEBSD:
|
352 |
+
|
353 |
+
def cpu_freq():
|
354 |
+
"""Return frequency metrics for CPUs. As of Dec 2018 only
|
355 |
+
CPU 0 appears to be supported by FreeBSD and all other cores
|
356 |
+
match the frequency of CPU 0.
|
357 |
+
"""
|
358 |
+
ret = []
|
359 |
+
num_cpus = cpu_count_logical()
|
360 |
+
for cpu in range(num_cpus):
|
361 |
+
try:
|
362 |
+
current, available_freq = cext.cpu_freq(cpu)
|
363 |
+
except NotImplementedError:
|
364 |
+
continue
|
365 |
+
if available_freq:
|
366 |
+
try:
|
367 |
+
min_freq = int(available_freq.split(" ")[-1].split("/")[0])
|
368 |
+
except (IndexError, ValueError):
|
369 |
+
min_freq = None
|
370 |
+
try:
|
371 |
+
max_freq = int(available_freq.split(" ")[0].split("/")[0])
|
372 |
+
except (IndexError, ValueError):
|
373 |
+
max_freq = None
|
374 |
+
ret.append(_common.scpufreq(current, min_freq, max_freq))
|
375 |
+
return ret
|
376 |
+
|
377 |
+
elif OPENBSD:
|
378 |
+
|
379 |
+
def cpu_freq():
|
380 |
+
curr = float(cext.cpu_freq())
|
381 |
+
return [_common.scpufreq(curr, 0.0, 0.0)]
|
382 |
+
|
383 |
+
|
384 |
+
# =====================================================================
|
385 |
+
# --- disks
|
386 |
+
# =====================================================================
|
387 |
+
|
388 |
+
|
389 |
+
def disk_partitions(all=False):
|
390 |
+
"""Return mounted disk partitions as a list of namedtuples.
|
391 |
+
'all' argument is ignored, see:
|
392 |
+
https://github.com/giampaolo/psutil/issues/906.
|
393 |
+
"""
|
394 |
+
retlist = []
|
395 |
+
partitions = cext.disk_partitions()
|
396 |
+
for partition in partitions:
|
397 |
+
device, mountpoint, fstype, opts = partition
|
398 |
+
maxfile = maxpath = None # set later
|
399 |
+
ntuple = _common.sdiskpart(
|
400 |
+
device, mountpoint, fstype, opts, maxfile, maxpath
|
401 |
+
)
|
402 |
+
retlist.append(ntuple)
|
403 |
+
return retlist
|
404 |
+
|
405 |
+
|
406 |
+
disk_usage = _psposix.disk_usage
|
407 |
+
disk_io_counters = cext.disk_io_counters
|
408 |
+
|
409 |
+
|
410 |
+
# =====================================================================
|
411 |
+
# --- network
|
412 |
+
# =====================================================================
|
413 |
+
|
414 |
+
|
415 |
+
net_io_counters = cext.net_io_counters
|
416 |
+
net_if_addrs = cext_posix.net_if_addrs
|
417 |
+
|
418 |
+
|
419 |
+
def net_if_stats():
|
420 |
+
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
421 |
+
names = net_io_counters().keys()
|
422 |
+
ret = {}
|
423 |
+
for name in names:
|
424 |
+
try:
|
425 |
+
mtu = cext_posix.net_if_mtu(name)
|
426 |
+
flags = cext_posix.net_if_flags(name)
|
427 |
+
duplex, speed = cext_posix.net_if_duplex_speed(name)
|
428 |
+
except OSError as err:
|
429 |
+
# https://github.com/giampaolo/psutil/issues/1279
|
430 |
+
if err.errno != errno.ENODEV:
|
431 |
+
raise
|
432 |
+
else:
|
433 |
+
if hasattr(_common, 'NicDuplex'):
|
434 |
+
duplex = _common.NicDuplex(duplex)
|
435 |
+
output_flags = ','.join(flags)
|
436 |
+
isup = 'running' in flags
|
437 |
+
ret[name] = _common.snicstats(
|
438 |
+
isup, duplex, speed, mtu, output_flags
|
439 |
+
)
|
440 |
+
return ret
|
441 |
+
|
442 |
+
|
443 |
+
def net_connections(kind):
|
444 |
+
"""System-wide network connections."""
|
445 |
+
if kind not in _common.conn_tmap:
|
446 |
+
raise ValueError(
|
447 |
+
"invalid %r kind argument; choose between %s"
|
448 |
+
% (kind, ', '.join([repr(x) for x in conn_tmap]))
|
449 |
+
)
|
450 |
+
families, types = conn_tmap[kind]
|
451 |
+
ret = set()
|
452 |
+
|
453 |
+
if OPENBSD:
|
454 |
+
rawlist = cext.net_connections(-1, families, types)
|
455 |
+
elif NETBSD:
|
456 |
+
rawlist = cext.net_connections(-1, kind)
|
457 |
+
else: # FreeBSD
|
458 |
+
rawlist = cext.net_connections(families, types)
|
459 |
+
|
460 |
+
for item in rawlist:
|
461 |
+
fd, fam, type, laddr, raddr, status, pid = item
|
462 |
+
nt = conn_to_ntuple(
|
463 |
+
fd, fam, type, laddr, raddr, status, TCP_STATUSES, pid
|
464 |
+
)
|
465 |
+
ret.add(nt)
|
466 |
+
return list(ret)
|
467 |
+
|
468 |
+
|
469 |
+
# =====================================================================
|
470 |
+
# --- sensors
|
471 |
+
# =====================================================================
|
472 |
+
|
473 |
+
|
474 |
+
if FREEBSD:
|
475 |
+
|
476 |
+
def sensors_battery():
|
477 |
+
"""Return battery info."""
|
478 |
+
try:
|
479 |
+
percent, minsleft, power_plugged = cext.sensors_battery()
|
480 |
+
except NotImplementedError:
|
481 |
+
# See: https://github.com/giampaolo/psutil/issues/1074
|
482 |
+
return None
|
483 |
+
power_plugged = power_plugged == 1
|
484 |
+
if power_plugged:
|
485 |
+
secsleft = _common.POWER_TIME_UNLIMITED
|
486 |
+
elif minsleft == -1:
|
487 |
+
secsleft = _common.POWER_TIME_UNKNOWN
|
488 |
+
else:
|
489 |
+
secsleft = minsleft * 60
|
490 |
+
return _common.sbattery(percent, secsleft, power_plugged)
|
491 |
+
|
492 |
+
def sensors_temperatures():
|
493 |
+
"""Return CPU cores temperatures if available, else an empty dict."""
|
494 |
+
ret = defaultdict(list)
|
495 |
+
num_cpus = cpu_count_logical()
|
496 |
+
for cpu in range(num_cpus):
|
497 |
+
try:
|
498 |
+
current, high = cext.sensors_cpu_temperature(cpu)
|
499 |
+
if high <= 0:
|
500 |
+
high = None
|
501 |
+
name = "Core %s" % cpu
|
502 |
+
ret["coretemp"].append(
|
503 |
+
_common.shwtemp(name, current, high, high)
|
504 |
+
)
|
505 |
+
except NotImplementedError:
|
506 |
+
pass
|
507 |
+
|
508 |
+
return ret
|
509 |
+
|
510 |
+
|
511 |
+
# =====================================================================
|
512 |
+
# --- other system functions
|
513 |
+
# =====================================================================
|
514 |
+
|
515 |
+
|
516 |
+
def boot_time():
|
517 |
+
"""The system boot time expressed in seconds since the epoch."""
|
518 |
+
return cext.boot_time()
|
519 |
+
|
520 |
+
|
521 |
+
def users():
|
522 |
+
"""Return currently connected users as a list of namedtuples."""
|
523 |
+
retlist = []
|
524 |
+
rawlist = cext.users()
|
525 |
+
for item in rawlist:
|
526 |
+
user, tty, hostname, tstamp, pid = item
|
527 |
+
if pid == -1:
|
528 |
+
assert OPENBSD
|
529 |
+
pid = None
|
530 |
+
if tty == '~':
|
531 |
+
continue # reboot or shutdown
|
532 |
+
nt = _common.suser(user, tty or None, hostname, tstamp, pid)
|
533 |
+
retlist.append(nt)
|
534 |
+
return retlist
|
535 |
+
|
536 |
+
|
537 |
+
# =====================================================================
|
538 |
+
# --- processes
|
539 |
+
# =====================================================================
|
540 |
+
|
541 |
+
|
542 |
+
@memoize
|
543 |
+
def _pid_0_exists():
|
544 |
+
try:
|
545 |
+
Process(0).name()
|
546 |
+
except NoSuchProcess:
|
547 |
+
return False
|
548 |
+
except AccessDenied:
|
549 |
+
return True
|
550 |
+
else:
|
551 |
+
return True
|
552 |
+
|
553 |
+
|
554 |
+
def pids():
|
555 |
+
"""Returns a list of PIDs currently running on the system."""
|
556 |
+
ret = cext.pids()
|
557 |
+
if OPENBSD and (0 not in ret) and _pid_0_exists():
|
558 |
+
# On OpenBSD the kernel does not return PID 0 (neither does
|
559 |
+
# ps) but it's actually querable (Process(0) will succeed).
|
560 |
+
ret.insert(0, 0)
|
561 |
+
return ret
|
562 |
+
|
563 |
+
|
564 |
+
if OPENBSD or NETBSD:
|
565 |
+
|
566 |
+
def pid_exists(pid):
|
567 |
+
"""Return True if pid exists."""
|
568 |
+
exists = _psposix.pid_exists(pid)
|
569 |
+
if not exists:
|
570 |
+
# We do this because _psposix.pid_exists() lies in case of
|
571 |
+
# zombie processes.
|
572 |
+
return pid in pids()
|
573 |
+
else:
|
574 |
+
return True
|
575 |
+
|
576 |
+
else:
|
577 |
+
pid_exists = _psposix.pid_exists
|
578 |
+
|
579 |
+
|
580 |
+
def is_zombie(pid):
|
581 |
+
try:
|
582 |
+
st = cext.proc_oneshot_info(pid)[kinfo_proc_map['status']]
|
583 |
+
return PROC_STATUSES.get(st) == _common.STATUS_ZOMBIE
|
584 |
+
except OSError:
|
585 |
+
return False
|
586 |
+
|
587 |
+
|
588 |
+
def wrap_exceptions(fun):
|
589 |
+
"""Decorator which translates bare OSError exceptions into
|
590 |
+
NoSuchProcess and AccessDenied.
|
591 |
+
"""
|
592 |
+
|
593 |
+
@functools.wraps(fun)
|
594 |
+
def wrapper(self, *args, **kwargs):
|
595 |
+
try:
|
596 |
+
return fun(self, *args, **kwargs)
|
597 |
+
except ProcessLookupError:
|
598 |
+
if is_zombie(self.pid):
|
599 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
600 |
+
else:
|
601 |
+
raise NoSuchProcess(self.pid, self._name)
|
602 |
+
except PermissionError:
|
603 |
+
raise AccessDenied(self.pid, self._name)
|
604 |
+
except OSError:
|
605 |
+
if self.pid == 0:
|
606 |
+
if 0 in pids():
|
607 |
+
raise AccessDenied(self.pid, self._name)
|
608 |
+
else:
|
609 |
+
raise
|
610 |
+
raise
|
611 |
+
|
612 |
+
return wrapper
|
613 |
+
|
614 |
+
|
615 |
+
@contextlib.contextmanager
|
616 |
+
def wrap_exceptions_procfs(inst):
|
617 |
+
"""Same as above, for routines relying on reading /proc fs."""
|
618 |
+
try:
|
619 |
+
yield
|
620 |
+
except (ProcessLookupError, FileNotFoundError):
|
621 |
+
# ENOENT (no such file or directory) gets raised on open().
|
622 |
+
# ESRCH (no such process) can get raised on read() if
|
623 |
+
# process is gone in meantime.
|
624 |
+
if is_zombie(inst.pid):
|
625 |
+
raise ZombieProcess(inst.pid, inst._name, inst._ppid)
|
626 |
+
else:
|
627 |
+
raise NoSuchProcess(inst.pid, inst._name)
|
628 |
+
except PermissionError:
|
629 |
+
raise AccessDenied(inst.pid, inst._name)
|
630 |
+
|
631 |
+
|
632 |
+
class Process:
|
633 |
+
"""Wrapper class around underlying C implementation."""
|
634 |
+
|
635 |
+
__slots__ = ["pid", "_name", "_ppid", "_cache"]
|
636 |
+
|
637 |
+
def __init__(self, pid):
|
638 |
+
self.pid = pid
|
639 |
+
self._name = None
|
640 |
+
self._ppid = None
|
641 |
+
|
642 |
+
def _assert_alive(self):
|
643 |
+
"""Raise NSP if the process disappeared on us."""
|
644 |
+
# For those C function who do not raise NSP, possibly returning
|
645 |
+
# incorrect or incomplete result.
|
646 |
+
cext.proc_name(self.pid)
|
647 |
+
|
648 |
+
@wrap_exceptions
|
649 |
+
@memoize_when_activated
|
650 |
+
def oneshot(self):
|
651 |
+
"""Retrieves multiple process info in one shot as a raw tuple."""
|
652 |
+
ret = cext.proc_oneshot_info(self.pid)
|
653 |
+
assert len(ret) == len(kinfo_proc_map)
|
654 |
+
return ret
|
655 |
+
|
656 |
+
def oneshot_enter(self):
|
657 |
+
self.oneshot.cache_activate(self)
|
658 |
+
|
659 |
+
def oneshot_exit(self):
|
660 |
+
self.oneshot.cache_deactivate(self)
|
661 |
+
|
662 |
+
@wrap_exceptions
|
663 |
+
def name(self):
|
664 |
+
name = self.oneshot()[kinfo_proc_map['name']]
|
665 |
+
return name if name is not None else cext.proc_name(self.pid)
|
666 |
+
|
667 |
+
@wrap_exceptions
|
668 |
+
def exe(self):
|
669 |
+
if FREEBSD:
|
670 |
+
if self.pid == 0:
|
671 |
+
return '' # else NSP
|
672 |
+
return cext.proc_exe(self.pid)
|
673 |
+
elif NETBSD:
|
674 |
+
if self.pid == 0:
|
675 |
+
# /proc/0 dir exists but /proc/0/exe doesn't
|
676 |
+
return ""
|
677 |
+
with wrap_exceptions_procfs(self):
|
678 |
+
return os.readlink("/proc/%s/exe" % self.pid)
|
679 |
+
else:
|
680 |
+
# OpenBSD: exe cannot be determined; references:
|
681 |
+
# https://chromium.googlesource.com/chromium/src/base/+/
|
682 |
+
# master/base_paths_posix.cc
|
683 |
+
# We try our best guess by using which against the first
|
684 |
+
# cmdline arg (may return None).
|
685 |
+
cmdline = self.cmdline()
|
686 |
+
if cmdline:
|
687 |
+
return which(cmdline[0]) or ""
|
688 |
+
else:
|
689 |
+
return ""
|
690 |
+
|
691 |
+
@wrap_exceptions
|
692 |
+
def cmdline(self):
|
693 |
+
if OPENBSD and self.pid == 0:
|
694 |
+
return [] # ...else it crashes
|
695 |
+
elif NETBSD:
|
696 |
+
# XXX - most of the times the underlying sysctl() call on
|
697 |
+
# NetBSD and OpenBSD returns a truncated string. Also
|
698 |
+
# /proc/pid/cmdline behaves the same so it looks like this
|
699 |
+
# is a kernel bug.
|
700 |
+
try:
|
701 |
+
return cext.proc_cmdline(self.pid)
|
702 |
+
except OSError as err:
|
703 |
+
if err.errno == errno.EINVAL:
|
704 |
+
if is_zombie(self.pid):
|
705 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
706 |
+
elif not pid_exists(self.pid):
|
707 |
+
raise NoSuchProcess(self.pid, self._name, self._ppid)
|
708 |
+
else:
|
709 |
+
# XXX: this happens with unicode tests. It means the C
|
710 |
+
# routine is unable to decode invalid unicode chars.
|
711 |
+
debug("ignoring %r and returning an empty list" % err)
|
712 |
+
return []
|
713 |
+
else:
|
714 |
+
raise
|
715 |
+
else:
|
716 |
+
return cext.proc_cmdline(self.pid)
|
717 |
+
|
718 |
+
@wrap_exceptions
|
719 |
+
def environ(self):
|
720 |
+
return cext.proc_environ(self.pid)
|
721 |
+
|
722 |
+
@wrap_exceptions
|
723 |
+
def terminal(self):
|
724 |
+
tty_nr = self.oneshot()[kinfo_proc_map['ttynr']]
|
725 |
+
tmap = _psposix.get_terminal_map()
|
726 |
+
try:
|
727 |
+
return tmap[tty_nr]
|
728 |
+
except KeyError:
|
729 |
+
return None
|
730 |
+
|
731 |
+
@wrap_exceptions
|
732 |
+
def ppid(self):
|
733 |
+
self._ppid = self.oneshot()[kinfo_proc_map['ppid']]
|
734 |
+
return self._ppid
|
735 |
+
|
736 |
+
@wrap_exceptions
|
737 |
+
def uids(self):
|
738 |
+
rawtuple = self.oneshot()
|
739 |
+
return _common.puids(
|
740 |
+
rawtuple[kinfo_proc_map['real_uid']],
|
741 |
+
rawtuple[kinfo_proc_map['effective_uid']],
|
742 |
+
rawtuple[kinfo_proc_map['saved_uid']],
|
743 |
+
)
|
744 |
+
|
745 |
+
@wrap_exceptions
|
746 |
+
def gids(self):
|
747 |
+
rawtuple = self.oneshot()
|
748 |
+
return _common.pgids(
|
749 |
+
rawtuple[kinfo_proc_map['real_gid']],
|
750 |
+
rawtuple[kinfo_proc_map['effective_gid']],
|
751 |
+
rawtuple[kinfo_proc_map['saved_gid']],
|
752 |
+
)
|
753 |
+
|
754 |
+
@wrap_exceptions
|
755 |
+
def cpu_times(self):
|
756 |
+
rawtuple = self.oneshot()
|
757 |
+
return _common.pcputimes(
|
758 |
+
rawtuple[kinfo_proc_map['user_time']],
|
759 |
+
rawtuple[kinfo_proc_map['sys_time']],
|
760 |
+
rawtuple[kinfo_proc_map['ch_user_time']],
|
761 |
+
rawtuple[kinfo_proc_map['ch_sys_time']],
|
762 |
+
)
|
763 |
+
|
764 |
+
if FREEBSD:
|
765 |
+
|
766 |
+
@wrap_exceptions
|
767 |
+
def cpu_num(self):
|
768 |
+
return self.oneshot()[kinfo_proc_map['cpunum']]
|
769 |
+
|
770 |
+
@wrap_exceptions
|
771 |
+
def memory_info(self):
|
772 |
+
rawtuple = self.oneshot()
|
773 |
+
return pmem(
|
774 |
+
rawtuple[kinfo_proc_map['rss']],
|
775 |
+
rawtuple[kinfo_proc_map['vms']],
|
776 |
+
rawtuple[kinfo_proc_map['memtext']],
|
777 |
+
rawtuple[kinfo_proc_map['memdata']],
|
778 |
+
rawtuple[kinfo_proc_map['memstack']],
|
779 |
+
)
|
780 |
+
|
781 |
+
memory_full_info = memory_info
|
782 |
+
|
783 |
+
@wrap_exceptions
|
784 |
+
def create_time(self):
|
785 |
+
return self.oneshot()[kinfo_proc_map['create_time']]
|
786 |
+
|
787 |
+
@wrap_exceptions
|
788 |
+
def num_threads(self):
|
789 |
+
if HAS_PROC_NUM_THREADS:
|
790 |
+
# FreeBSD
|
791 |
+
return cext.proc_num_threads(self.pid)
|
792 |
+
else:
|
793 |
+
return len(self.threads())
|
794 |
+
|
795 |
+
@wrap_exceptions
|
796 |
+
def num_ctx_switches(self):
|
797 |
+
rawtuple = self.oneshot()
|
798 |
+
return _common.pctxsw(
|
799 |
+
rawtuple[kinfo_proc_map['ctx_switches_vol']],
|
800 |
+
rawtuple[kinfo_proc_map['ctx_switches_unvol']],
|
801 |
+
)
|
802 |
+
|
803 |
+
@wrap_exceptions
|
804 |
+
def threads(self):
|
805 |
+
# Note: on OpenSBD this (/dev/mem) requires root access.
|
806 |
+
rawlist = cext.proc_threads(self.pid)
|
807 |
+
retlist = []
|
808 |
+
for thread_id, utime, stime in rawlist:
|
809 |
+
ntuple = _common.pthread(thread_id, utime, stime)
|
810 |
+
retlist.append(ntuple)
|
811 |
+
if OPENBSD:
|
812 |
+
self._assert_alive()
|
813 |
+
return retlist
|
814 |
+
|
815 |
+
@wrap_exceptions
|
816 |
+
def connections(self, kind='inet'):
|
817 |
+
if kind not in conn_tmap:
|
818 |
+
raise ValueError(
|
819 |
+
"invalid %r kind argument; choose between %s"
|
820 |
+
% (kind, ', '.join([repr(x) for x in conn_tmap]))
|
821 |
+
)
|
822 |
+
families, types = conn_tmap[kind]
|
823 |
+
ret = []
|
824 |
+
|
825 |
+
if NETBSD:
|
826 |
+
rawlist = cext.net_connections(self.pid, kind)
|
827 |
+
elif OPENBSD:
|
828 |
+
rawlist = cext.net_connections(self.pid, families, types)
|
829 |
+
else:
|
830 |
+
rawlist = cext.proc_connections(self.pid, families, types)
|
831 |
+
|
832 |
+
for item in rawlist:
|
833 |
+
fd, fam, type, laddr, raddr, status = item[:6]
|
834 |
+
if FREEBSD:
|
835 |
+
if (fam not in families) or (type not in types):
|
836 |
+
continue
|
837 |
+
nt = conn_to_ntuple(
|
838 |
+
fd, fam, type, laddr, raddr, status, TCP_STATUSES
|
839 |
+
)
|
840 |
+
ret.append(nt)
|
841 |
+
|
842 |
+
self._assert_alive()
|
843 |
+
return ret
|
844 |
+
|
845 |
+
@wrap_exceptions
|
846 |
+
def wait(self, timeout=None):
|
847 |
+
return _psposix.wait_pid(self.pid, timeout, self._name)
|
848 |
+
|
849 |
+
@wrap_exceptions
|
850 |
+
def nice_get(self):
|
851 |
+
return cext_posix.getpriority(self.pid)
|
852 |
+
|
853 |
+
@wrap_exceptions
|
854 |
+
def nice_set(self, value):
|
855 |
+
return cext_posix.setpriority(self.pid, value)
|
856 |
+
|
857 |
+
@wrap_exceptions
|
858 |
+
def status(self):
|
859 |
+
code = self.oneshot()[kinfo_proc_map['status']]
|
860 |
+
# XXX is '?' legit? (we're not supposed to return it anyway)
|
861 |
+
return PROC_STATUSES.get(code, '?')
|
862 |
+
|
863 |
+
@wrap_exceptions
|
864 |
+
def io_counters(self):
|
865 |
+
rawtuple = self.oneshot()
|
866 |
+
return _common.pio(
|
867 |
+
rawtuple[kinfo_proc_map['read_io_count']],
|
868 |
+
rawtuple[kinfo_proc_map['write_io_count']],
|
869 |
+
-1,
|
870 |
+
-1,
|
871 |
+
)
|
872 |
+
|
873 |
+
@wrap_exceptions
|
874 |
+
def cwd(self):
|
875 |
+
"""Return process current working directory."""
|
876 |
+
# sometimes we get an empty string, in which case we turn
|
877 |
+
# it into None
|
878 |
+
if OPENBSD and self.pid == 0:
|
879 |
+
return "" # ...else it would raise EINVAL
|
880 |
+
elif NETBSD or HAS_PROC_OPEN_FILES:
|
881 |
+
# FreeBSD < 8 does not support functions based on
|
882 |
+
# kinfo_getfile() and kinfo_getvmmap()
|
883 |
+
return cext.proc_cwd(self.pid)
|
884 |
+
else:
|
885 |
+
raise NotImplementedError(
|
886 |
+
"supported only starting from FreeBSD 8" if FREEBSD else ""
|
887 |
+
)
|
888 |
+
|
889 |
+
nt_mmap_grouped = namedtuple(
|
890 |
+
'mmap', 'path rss, private, ref_count, shadow_count'
|
891 |
+
)
|
892 |
+
nt_mmap_ext = namedtuple(
|
893 |
+
'mmap', 'addr, perms path rss, private, ref_count, shadow_count'
|
894 |
+
)
|
895 |
+
|
896 |
+
def _not_implemented(self):
|
897 |
+
raise NotImplementedError
|
898 |
+
|
899 |
+
# FreeBSD < 8 does not support functions based on kinfo_getfile()
|
900 |
+
# and kinfo_getvmmap()
|
901 |
+
if HAS_PROC_OPEN_FILES:
|
902 |
+
|
903 |
+
@wrap_exceptions
|
904 |
+
def open_files(self):
|
905 |
+
"""Return files opened by process as a list of namedtuples."""
|
906 |
+
rawlist = cext.proc_open_files(self.pid)
|
907 |
+
return [_common.popenfile(path, fd) for path, fd in rawlist]
|
908 |
+
|
909 |
+
else:
|
910 |
+
open_files = _not_implemented
|
911 |
+
|
912 |
+
# FreeBSD < 8 does not support functions based on kinfo_getfile()
|
913 |
+
# and kinfo_getvmmap()
|
914 |
+
if HAS_PROC_NUM_FDS:
|
915 |
+
|
916 |
+
@wrap_exceptions
|
917 |
+
def num_fds(self):
|
918 |
+
"""Return the number of file descriptors opened by this process."""
|
919 |
+
ret = cext.proc_num_fds(self.pid)
|
920 |
+
if NETBSD:
|
921 |
+
self._assert_alive()
|
922 |
+
return ret
|
923 |
+
|
924 |
+
else:
|
925 |
+
num_fds = _not_implemented
|
926 |
+
|
927 |
+
# --- FreeBSD only APIs
|
928 |
+
|
929 |
+
if FREEBSD:
|
930 |
+
|
931 |
+
@wrap_exceptions
|
932 |
+
def cpu_affinity_get(self):
|
933 |
+
return cext.proc_cpu_affinity_get(self.pid)
|
934 |
+
|
935 |
+
@wrap_exceptions
|
936 |
+
def cpu_affinity_set(self, cpus):
|
937 |
+
# Pre-emptively check if CPUs are valid because the C
|
938 |
+
# function has a weird behavior in case of invalid CPUs,
|
939 |
+
# see: https://github.com/giampaolo/psutil/issues/586
|
940 |
+
allcpus = tuple(range(len(per_cpu_times())))
|
941 |
+
for cpu in cpus:
|
942 |
+
if cpu not in allcpus:
|
943 |
+
raise ValueError(
|
944 |
+
"invalid CPU #%i (choose between %s)" % (cpu, allcpus)
|
945 |
+
)
|
946 |
+
try:
|
947 |
+
cext.proc_cpu_affinity_set(self.pid, cpus)
|
948 |
+
except OSError as err:
|
949 |
+
# 'man cpuset_setaffinity' about EDEADLK:
|
950 |
+
# <<the call would leave a thread without a valid CPU to run
|
951 |
+
# on because the set does not overlap with the thread's
|
952 |
+
# anonymous mask>>
|
953 |
+
if err.errno in (errno.EINVAL, errno.EDEADLK):
|
954 |
+
for cpu in cpus:
|
955 |
+
if cpu not in allcpus:
|
956 |
+
raise ValueError(
|
957 |
+
"invalid CPU #%i (choose between %s)"
|
958 |
+
% (cpu, allcpus)
|
959 |
+
)
|
960 |
+
raise
|
961 |
+
|
962 |
+
@wrap_exceptions
|
963 |
+
def memory_maps(self):
|
964 |
+
return cext.proc_memory_maps(self.pid)
|
965 |
+
|
966 |
+
@wrap_exceptions
|
967 |
+
def rlimit(self, resource, limits=None):
|
968 |
+
if limits is None:
|
969 |
+
return cext.proc_getrlimit(self.pid, resource)
|
970 |
+
else:
|
971 |
+
if len(limits) != 2:
|
972 |
+
raise ValueError(
|
973 |
+
"second argument must be a (soft, hard) tuple, got %s"
|
974 |
+
% repr(limits)
|
975 |
+
)
|
976 |
+
soft, hard = limits
|
977 |
+
return cext.proc_setrlimit(self.pid, resource, soft, hard)
|
env-llmeval/lib/python3.10/site-packages/psutil/_pslinux.py
ADDED
@@ -0,0 +1,2366 @@
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""Linux platform implementation."""
|
6 |
+
|
7 |
+
from __future__ import division
|
8 |
+
|
9 |
+
import base64
|
10 |
+
import collections
|
11 |
+
import errno
|
12 |
+
import functools
|
13 |
+
import glob
|
14 |
+
import os
|
15 |
+
import re
|
16 |
+
import socket
|
17 |
+
import struct
|
18 |
+
import sys
|
19 |
+
import warnings
|
20 |
+
from collections import defaultdict
|
21 |
+
from collections import namedtuple
|
22 |
+
|
23 |
+
from . import _common
|
24 |
+
from . import _psposix
|
25 |
+
from . import _psutil_linux as cext
|
26 |
+
from . import _psutil_posix as cext_posix
|
27 |
+
from ._common import NIC_DUPLEX_FULL
|
28 |
+
from ._common import NIC_DUPLEX_HALF
|
29 |
+
from ._common import NIC_DUPLEX_UNKNOWN
|
30 |
+
from ._common import AccessDenied
|
31 |
+
from ._common import NoSuchProcess
|
32 |
+
from ._common import ZombieProcess
|
33 |
+
from ._common import bcat
|
34 |
+
from ._common import cat
|
35 |
+
from ._common import debug
|
36 |
+
from ._common import decode
|
37 |
+
from ._common import get_procfs_path
|
38 |
+
from ._common import isfile_strict
|
39 |
+
from ._common import memoize
|
40 |
+
from ._common import memoize_when_activated
|
41 |
+
from ._common import open_binary
|
42 |
+
from ._common import open_text
|
43 |
+
from ._common import parse_environ_block
|
44 |
+
from ._common import path_exists_strict
|
45 |
+
from ._common import supports_ipv6
|
46 |
+
from ._common import usage_percent
|
47 |
+
from ._compat import PY3
|
48 |
+
from ._compat import FileNotFoundError
|
49 |
+
from ._compat import PermissionError
|
50 |
+
from ._compat import ProcessLookupError
|
51 |
+
from ._compat import b
|
52 |
+
from ._compat import basestring
|
53 |
+
|
54 |
+
|
55 |
+
if PY3:
|
56 |
+
import enum
|
57 |
+
else:
|
58 |
+
enum = None
|
59 |
+
|
60 |
+
|
61 |
+
# fmt: off
|
62 |
+
__extra__all__ = [
|
63 |
+
#
|
64 |
+
'PROCFS_PATH',
|
65 |
+
# io prio constants
|
66 |
+
"IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
|
67 |
+
"IOPRIO_CLASS_IDLE",
|
68 |
+
# connection status constants
|
69 |
+
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
|
70 |
+
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
|
71 |
+
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING",
|
72 |
+
]
|
73 |
+
# fmt: on
|
74 |
+
|
75 |
+
|
76 |
+
# =====================================================================
|
77 |
+
# --- globals
|
78 |
+
# =====================================================================
|
79 |
+
|
80 |
+
|
81 |
+
POWER_SUPPLY_PATH = "/sys/class/power_supply"
|
82 |
+
HAS_PROC_SMAPS = os.path.exists('/proc/%s/smaps' % os.getpid())
|
83 |
+
HAS_PROC_SMAPS_ROLLUP = os.path.exists('/proc/%s/smaps_rollup' % os.getpid())
|
84 |
+
HAS_PROC_IO_PRIORITY = hasattr(cext, "proc_ioprio_get")
|
85 |
+
HAS_CPU_AFFINITY = hasattr(cext, "proc_cpu_affinity_get")
|
86 |
+
|
87 |
+
# Number of clock ticks per second
|
88 |
+
CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
|
89 |
+
PAGESIZE = cext_posix.getpagesize()
|
90 |
+
BOOT_TIME = None # set later
|
91 |
+
LITTLE_ENDIAN = sys.byteorder == 'little'
|
92 |
+
|
93 |
+
# "man iostat" states that sectors are equivalent with blocks and have
|
94 |
+
# a size of 512 bytes. Despite this value can be queried at runtime
|
95 |
+
# via /sys/block/{DISK}/queue/hw_sector_size and results may vary
|
96 |
+
# between 1k, 2k, or 4k... 512 appears to be a magic constant used
|
97 |
+
# throughout Linux source code:
|
98 |
+
# * https://stackoverflow.com/a/38136179/376587
|
99 |
+
# * https://lists.gt.net/linux/kernel/2241060
|
100 |
+
# * https://github.com/giampaolo/psutil/issues/1305
|
101 |
+
# * https://github.com/torvalds/linux/blob/
|
102 |
+
# 4f671fe2f9523a1ea206f63fe60a7c7b3a56d5c7/include/linux/bio.h#L99
|
103 |
+
# * https://lkml.org/lkml/2015/8/17/234
|
104 |
+
DISK_SECTOR_SIZE = 512
|
105 |
+
|
106 |
+
if enum is None:
|
107 |
+
AF_LINK = socket.AF_PACKET
|
108 |
+
else:
|
109 |
+
AddressFamily = enum.IntEnum(
|
110 |
+
'AddressFamily', {'AF_LINK': int(socket.AF_PACKET)}
|
111 |
+
)
|
112 |
+
AF_LINK = AddressFamily.AF_LINK
|
113 |
+
|
114 |
+
# ioprio_* constants http://linux.die.net/man/2/ioprio_get
|
115 |
+
if enum is None:
|
116 |
+
IOPRIO_CLASS_NONE = 0
|
117 |
+
IOPRIO_CLASS_RT = 1
|
118 |
+
IOPRIO_CLASS_BE = 2
|
119 |
+
IOPRIO_CLASS_IDLE = 3
|
120 |
+
else:
|
121 |
+
|
122 |
+
class IOPriority(enum.IntEnum):
|
123 |
+
IOPRIO_CLASS_NONE = 0
|
124 |
+
IOPRIO_CLASS_RT = 1
|
125 |
+
IOPRIO_CLASS_BE = 2
|
126 |
+
IOPRIO_CLASS_IDLE = 3
|
127 |
+
|
128 |
+
globals().update(IOPriority.__members__)
|
129 |
+
|
130 |
+
# See:
|
131 |
+
# https://github.com/torvalds/linux/blame/master/fs/proc/array.c
|
132 |
+
# ...and (TASK_* constants):
|
133 |
+
# https://github.com/torvalds/linux/blob/master/include/linux/sched.h
|
134 |
+
PROC_STATUSES = {
|
135 |
+
"R": _common.STATUS_RUNNING,
|
136 |
+
"S": _common.STATUS_SLEEPING,
|
137 |
+
"D": _common.STATUS_DISK_SLEEP,
|
138 |
+
"T": _common.STATUS_STOPPED,
|
139 |
+
"t": _common.STATUS_TRACING_STOP,
|
140 |
+
"Z": _common.STATUS_ZOMBIE,
|
141 |
+
"X": _common.STATUS_DEAD,
|
142 |
+
"x": _common.STATUS_DEAD,
|
143 |
+
"K": _common.STATUS_WAKE_KILL,
|
144 |
+
"W": _common.STATUS_WAKING,
|
145 |
+
"I": _common.STATUS_IDLE,
|
146 |
+
"P": _common.STATUS_PARKED,
|
147 |
+
}
|
148 |
+
|
149 |
+
# https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h
|
150 |
+
TCP_STATUSES = {
|
151 |
+
"01": _common.CONN_ESTABLISHED,
|
152 |
+
"02": _common.CONN_SYN_SENT,
|
153 |
+
"03": _common.CONN_SYN_RECV,
|
154 |
+
"04": _common.CONN_FIN_WAIT1,
|
155 |
+
"05": _common.CONN_FIN_WAIT2,
|
156 |
+
"06": _common.CONN_TIME_WAIT,
|
157 |
+
"07": _common.CONN_CLOSE,
|
158 |
+
"08": _common.CONN_CLOSE_WAIT,
|
159 |
+
"09": _common.CONN_LAST_ACK,
|
160 |
+
"0A": _common.CONN_LISTEN,
|
161 |
+
"0B": _common.CONN_CLOSING,
|
162 |
+
}
|
163 |
+
|
164 |
+
|
165 |
+
# =====================================================================
|
166 |
+
# --- named tuples
|
167 |
+
# =====================================================================
|
168 |
+
|
169 |
+
|
170 |
+
# fmt: off
|
171 |
+
# psutil.virtual_memory()
|
172 |
+
svmem = namedtuple(
|
173 |
+
'svmem', ['total', 'available', 'percent', 'used', 'free',
|
174 |
+
'active', 'inactive', 'buffers', 'cached', 'shared', 'slab'])
|
175 |
+
# psutil.disk_io_counters()
|
176 |
+
sdiskio = namedtuple(
|
177 |
+
'sdiskio', ['read_count', 'write_count',
|
178 |
+
'read_bytes', 'write_bytes',
|
179 |
+
'read_time', 'write_time',
|
180 |
+
'read_merged_count', 'write_merged_count',
|
181 |
+
'busy_time'])
|
182 |
+
# psutil.Process().open_files()
|
183 |
+
popenfile = namedtuple(
|
184 |
+
'popenfile', ['path', 'fd', 'position', 'mode', 'flags'])
|
185 |
+
# psutil.Process().memory_info()
|
186 |
+
pmem = namedtuple('pmem', 'rss vms shared text lib data dirty')
|
187 |
+
# psutil.Process().memory_full_info()
|
188 |
+
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', 'pss', 'swap'))
|
189 |
+
# psutil.Process().memory_maps(grouped=True)
|
190 |
+
pmmap_grouped = namedtuple(
|
191 |
+
'pmmap_grouped',
|
192 |
+
['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty',
|
193 |
+
'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap'])
|
194 |
+
# psutil.Process().memory_maps(grouped=False)
|
195 |
+
pmmap_ext = namedtuple(
|
196 |
+
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
|
197 |
+
# psutil.Process.io_counters()
|
198 |
+
pio = namedtuple('pio', ['read_count', 'write_count',
|
199 |
+
'read_bytes', 'write_bytes',
|
200 |
+
'read_chars', 'write_chars'])
|
201 |
+
# psutil.Process.cpu_times()
|
202 |
+
pcputimes = namedtuple('pcputimes',
|
203 |
+
['user', 'system', 'children_user', 'children_system',
|
204 |
+
'iowait'])
|
205 |
+
# fmt: on
|
206 |
+
|
207 |
+
|
208 |
+
# =====================================================================
|
209 |
+
# --- utils
|
210 |
+
# =====================================================================
|
211 |
+
|
212 |
+
|
213 |
+
def readlink(path):
|
214 |
+
"""Wrapper around os.readlink()."""
|
215 |
+
assert isinstance(path, basestring), path
|
216 |
+
path = os.readlink(path)
|
217 |
+
# readlink() might return paths containing null bytes ('\x00')
|
218 |
+
# resulting in "TypeError: must be encoded string without NULL
|
219 |
+
# bytes, not str" errors when the string is passed to other
|
220 |
+
# fs-related functions (os.*, open(), ...).
|
221 |
+
# Apparently everything after '\x00' is garbage (we can have
|
222 |
+
# ' (deleted)', 'new' and possibly others), see:
|
223 |
+
# https://github.com/giampaolo/psutil/issues/717
|
224 |
+
path = path.split('\x00')[0]
|
225 |
+
# Certain paths have ' (deleted)' appended. Usually this is
|
226 |
+
# bogus as the file actually exists. Even if it doesn't we
|
227 |
+
# don't care.
|
228 |
+
if path.endswith(' (deleted)') and not path_exists_strict(path):
|
229 |
+
path = path[:-10]
|
230 |
+
return path
|
231 |
+
|
232 |
+
|
233 |
+
def file_flags_to_mode(flags):
|
234 |
+
"""Convert file's open() flags into a readable string.
|
235 |
+
Used by Process.open_files().
|
236 |
+
"""
|
237 |
+
modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
|
238 |
+
mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
|
239 |
+
if flags & os.O_APPEND:
|
240 |
+
mode = mode.replace('w', 'a', 1)
|
241 |
+
mode = mode.replace('w+', 'r+')
|
242 |
+
# possible values: r, w, a, r+, a+
|
243 |
+
return mode
|
244 |
+
|
245 |
+
|
246 |
+
def is_storage_device(name):
|
247 |
+
"""Return True if the given name refers to a root device (e.g.
|
248 |
+
"sda", "nvme0n1") as opposed to a logical partition (e.g. "sda1",
|
249 |
+
"nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
|
250 |
+
return True.
|
251 |
+
"""
|
252 |
+
# Re-adapted from iostat source code, see:
|
253 |
+
# https://github.com/sysstat/sysstat/blob/
|
254 |
+
# 97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
|
255 |
+
# Some devices may have a slash in their name (e.g. cciss/c0d0...).
|
256 |
+
name = name.replace('/', '!')
|
257 |
+
including_virtual = True
|
258 |
+
if including_virtual:
|
259 |
+
path = "/sys/block/%s" % name
|
260 |
+
else:
|
261 |
+
path = "/sys/block/%s/device" % name
|
262 |
+
return os.access(path, os.F_OK)
|
263 |
+
|
264 |
+
|
265 |
+
@memoize
|
266 |
+
def set_scputimes_ntuple(procfs_path):
|
267 |
+
"""Set a namedtuple of variable fields depending on the CPU times
|
268 |
+
available on this Linux kernel version which may be:
|
269 |
+
(user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
|
270 |
+
[guest_nice]]])
|
271 |
+
Used by cpu_times() function.
|
272 |
+
"""
|
273 |
+
global scputimes
|
274 |
+
with open_binary('%s/stat' % procfs_path) as f:
|
275 |
+
values = f.readline().split()[1:]
|
276 |
+
fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
|
277 |
+
vlen = len(values)
|
278 |
+
if vlen >= 8:
|
279 |
+
# Linux >= 2.6.11
|
280 |
+
fields.append('steal')
|
281 |
+
if vlen >= 9:
|
282 |
+
# Linux >= 2.6.24
|
283 |
+
fields.append('guest')
|
284 |
+
if vlen >= 10:
|
285 |
+
# Linux >= 3.2.0
|
286 |
+
fields.append('guest_nice')
|
287 |
+
scputimes = namedtuple('scputimes', fields)
|
288 |
+
|
289 |
+
|
290 |
+
try:
|
291 |
+
set_scputimes_ntuple("/proc")
|
292 |
+
except Exception as err: # noqa: BLE001
|
293 |
+
# Don't want to crash at import time.
|
294 |
+
debug("ignoring exception on import: %r" % err)
|
295 |
+
scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)
|
296 |
+
|
297 |
+
|
298 |
+
# =====================================================================
|
299 |
+
# --- prlimit
|
300 |
+
# =====================================================================
|
301 |
+
|
302 |
+
# Backport of resource.prlimit() for Python 2. Originally this was done
|
303 |
+
# in C, but CentOS-6 which we use to create manylinux wheels is too old
|
304 |
+
# and does not support prlimit() syscall. As such the resulting wheel
|
305 |
+
# would not include prlimit(), even when installed on newer systems.
|
306 |
+
# This is the only part of psutil using ctypes.
|
307 |
+
|
308 |
+
prlimit = None
|
309 |
+
try:
|
310 |
+
from resource import prlimit # python >= 3.4
|
311 |
+
except ImportError:
|
312 |
+
import ctypes
|
313 |
+
|
314 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
315 |
+
|
316 |
+
if hasattr(libc, "prlimit"):
|
317 |
+
|
318 |
+
def prlimit(pid, resource_, limits=None):
|
319 |
+
class StructRlimit(ctypes.Structure):
|
320 |
+
_fields_ = [
|
321 |
+
('rlim_cur', ctypes.c_longlong),
|
322 |
+
('rlim_max', ctypes.c_longlong),
|
323 |
+
]
|
324 |
+
|
325 |
+
current = StructRlimit()
|
326 |
+
if limits is None:
|
327 |
+
# get
|
328 |
+
ret = libc.prlimit(pid, resource_, None, ctypes.byref(current))
|
329 |
+
else:
|
330 |
+
# set
|
331 |
+
new = StructRlimit()
|
332 |
+
new.rlim_cur = limits[0]
|
333 |
+
new.rlim_max = limits[1]
|
334 |
+
ret = libc.prlimit(
|
335 |
+
pid, resource_, ctypes.byref(new), ctypes.byref(current)
|
336 |
+
)
|
337 |
+
|
338 |
+
if ret != 0:
|
339 |
+
errno_ = ctypes.get_errno()
|
340 |
+
raise OSError(errno_, os.strerror(errno_))
|
341 |
+
return (current.rlim_cur, current.rlim_max)
|
342 |
+
|
343 |
+
|
344 |
+
if prlimit is not None:
|
345 |
+
__extra__all__.extend(
|
346 |
+
[x for x in dir(cext) if x.startswith('RLIM') and x.isupper()]
|
347 |
+
)
|
348 |
+
|
349 |
+
|
350 |
+
# =====================================================================
|
351 |
+
# --- system memory
|
352 |
+
# =====================================================================
|
353 |
+
|
354 |
+
|
355 |
+
def calculate_avail_vmem(mems):
|
356 |
+
"""Fallback for kernels < 3.14 where /proc/meminfo does not provide
|
357 |
+
"MemAvailable", see:
|
358 |
+
https://blog.famzah.net/2014/09/24/.
|
359 |
+
|
360 |
+
This code reimplements the algorithm outlined here:
|
361 |
+
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
|
362 |
+
commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
|
363 |
+
|
364 |
+
We use this function also when "MemAvailable" returns 0 (possibly a
|
365 |
+
kernel bug, see: https://github.com/giampaolo/psutil/issues/1915).
|
366 |
+
In that case this routine matches "free" CLI tool result ("available"
|
367 |
+
column).
|
368 |
+
|
369 |
+
XXX: on recent kernels this calculation may differ by ~1.5% compared
|
370 |
+
to "MemAvailable:", as it's calculated slightly differently.
|
371 |
+
It is still way more realistic than doing (free + cached) though.
|
372 |
+
See:
|
373 |
+
* https://gitlab.com/procps-ng/procps/issues/42
|
374 |
+
* https://github.com/famzah/linux-memavailable-procfs/issues/2
|
375 |
+
"""
|
376 |
+
# Note about "fallback" value. According to:
|
377 |
+
# https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
|
378 |
+
# commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
|
379 |
+
# ...long ago "available" memory was calculated as (free + cached),
|
380 |
+
# We use fallback when one of these is missing from /proc/meminfo:
|
381 |
+
# "Active(file)": introduced in 2.6.28 / Dec 2008
|
382 |
+
# "Inactive(file)": introduced in 2.6.28 / Dec 2008
|
383 |
+
# "SReclaimable": introduced in 2.6.19 / Nov 2006
|
384 |
+
# /proc/zoneinfo: introduced in 2.6.13 / Aug 2005
|
385 |
+
free = mems[b'MemFree:']
|
386 |
+
fallback = free + mems.get(b"Cached:", 0)
|
387 |
+
try:
|
388 |
+
lru_active_file = mems[b'Active(file):']
|
389 |
+
lru_inactive_file = mems[b'Inactive(file):']
|
390 |
+
slab_reclaimable = mems[b'SReclaimable:']
|
391 |
+
except KeyError as err:
|
392 |
+
debug(
|
393 |
+
"%s is missing from /proc/meminfo; using an approximation for "
|
394 |
+
"calculating available memory"
|
395 |
+
% err.args[0]
|
396 |
+
)
|
397 |
+
return fallback
|
398 |
+
try:
|
399 |
+
f = open_binary('%s/zoneinfo' % get_procfs_path())
|
400 |
+
except IOError:
|
401 |
+
return fallback # kernel 2.6.13
|
402 |
+
|
403 |
+
watermark_low = 0
|
404 |
+
with f:
|
405 |
+
for line in f:
|
406 |
+
line = line.strip()
|
407 |
+
if line.startswith(b'low'):
|
408 |
+
watermark_low += int(line.split()[1])
|
409 |
+
watermark_low *= PAGESIZE
|
410 |
+
|
411 |
+
avail = free - watermark_low
|
412 |
+
pagecache = lru_active_file + lru_inactive_file
|
413 |
+
pagecache -= min(pagecache / 2, watermark_low)
|
414 |
+
avail += pagecache
|
415 |
+
avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low)
|
416 |
+
return int(avail)
|
417 |
+
|
418 |
+
|
419 |
+
def virtual_memory():
|
420 |
+
"""Report virtual memory stats.
|
421 |
+
This implementation mimicks procps-ng-3.3.12, aka "free" CLI tool:
|
422 |
+
https://gitlab.com/procps-ng/procps/blob/
|
423 |
+
24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L778-791
|
424 |
+
The returned values are supposed to match both "free" and "vmstat -s"
|
425 |
+
CLI tools.
|
426 |
+
"""
|
427 |
+
missing_fields = []
|
428 |
+
mems = {}
|
429 |
+
with open_binary('%s/meminfo' % get_procfs_path()) as f:
|
430 |
+
for line in f:
|
431 |
+
fields = line.split()
|
432 |
+
mems[fields[0]] = int(fields[1]) * 1024
|
433 |
+
|
434 |
+
# /proc doc states that the available fields in /proc/meminfo vary
|
435 |
+
# by architecture and compile options, but these 3 values are also
|
436 |
+
# returned by sysinfo(2); as such we assume they are always there.
|
437 |
+
total = mems[b'MemTotal:']
|
438 |
+
free = mems[b'MemFree:']
|
439 |
+
try:
|
440 |
+
buffers = mems[b'Buffers:']
|
441 |
+
except KeyError:
|
442 |
+
# https://github.com/giampaolo/psutil/issues/1010
|
443 |
+
buffers = 0
|
444 |
+
missing_fields.append('buffers')
|
445 |
+
try:
|
446 |
+
cached = mems[b"Cached:"]
|
447 |
+
except KeyError:
|
448 |
+
cached = 0
|
449 |
+
missing_fields.append('cached')
|
450 |
+
else:
|
451 |
+
# "free" cmdline utility sums reclaimable to cached.
|
452 |
+
# Older versions of procps used to add slab memory instead.
|
453 |
+
# This got changed in:
|
454 |
+
# https://gitlab.com/procps-ng/procps/commit/
|
455 |
+
# 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
|
456 |
+
cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19
|
457 |
+
|
458 |
+
try:
|
459 |
+
shared = mems[b'Shmem:'] # since kernel 2.6.32
|
460 |
+
except KeyError:
|
461 |
+
try:
|
462 |
+
shared = mems[b'MemShared:'] # kernels 2.4
|
463 |
+
except KeyError:
|
464 |
+
shared = 0
|
465 |
+
missing_fields.append('shared')
|
466 |
+
|
467 |
+
try:
|
468 |
+
active = mems[b"Active:"]
|
469 |
+
except KeyError:
|
470 |
+
active = 0
|
471 |
+
missing_fields.append('active')
|
472 |
+
|
473 |
+
try:
|
474 |
+
inactive = mems[b"Inactive:"]
|
475 |
+
except KeyError:
|
476 |
+
try:
|
477 |
+
inactive = (
|
478 |
+
mems[b"Inact_dirty:"]
|
479 |
+
+ mems[b"Inact_clean:"]
|
480 |
+
+ mems[b"Inact_laundry:"]
|
481 |
+
)
|
482 |
+
except KeyError:
|
483 |
+
inactive = 0
|
484 |
+
missing_fields.append('inactive')
|
485 |
+
|
486 |
+
try:
|
487 |
+
slab = mems[b"Slab:"]
|
488 |
+
except KeyError:
|
489 |
+
slab = 0
|
490 |
+
|
491 |
+
used = total - free - cached - buffers
|
492 |
+
if used < 0:
|
493 |
+
# May be symptomatic of running within a LCX container where such
|
494 |
+
# values will be dramatically distorted over those of the host.
|
495 |
+
used = total - free
|
496 |
+
|
497 |
+
# - starting from 4.4.0 we match free's "available" column.
|
498 |
+
# Before 4.4.0 we calculated it as (free + buffers + cached)
|
499 |
+
# which matched htop.
|
500 |
+
# - free and htop available memory differs as per:
|
501 |
+
# http://askubuntu.com/a/369589
|
502 |
+
# http://unix.stackexchange.com/a/65852/168884
|
503 |
+
# - MemAvailable has been introduced in kernel 3.14
|
504 |
+
try:
|
505 |
+
avail = mems[b'MemAvailable:']
|
506 |
+
except KeyError:
|
507 |
+
avail = calculate_avail_vmem(mems)
|
508 |
+
else:
|
509 |
+
if avail == 0:
|
510 |
+
# Yes, it can happen (probably a kernel bug):
|
511 |
+
# https://github.com/giampaolo/psutil/issues/1915
|
512 |
+
# In this case "free" CLI tool makes an estimate. We do the same,
|
513 |
+
# and it matches "free" CLI tool.
|
514 |
+
avail = calculate_avail_vmem(mems)
|
515 |
+
|
516 |
+
if avail < 0:
|
517 |
+
avail = 0
|
518 |
+
missing_fields.append('available')
|
519 |
+
elif avail > total:
|
520 |
+
# If avail is greater than total or our calculation overflows,
|
521 |
+
# that's symptomatic of running within a LCX container where such
|
522 |
+
# values will be dramatically distorted over those of the host.
|
523 |
+
# https://gitlab.com/procps-ng/procps/blob/
|
524 |
+
# 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764
|
525 |
+
avail = free
|
526 |
+
|
527 |
+
percent = usage_percent((total - avail), total, round_=1)
|
528 |
+
|
529 |
+
# Warn about missing metrics which are set to 0.
|
530 |
+
if missing_fields:
|
531 |
+
msg = "%s memory stats couldn't be determined and %s set to 0" % (
|
532 |
+
", ".join(missing_fields),
|
533 |
+
"was" if len(missing_fields) == 1 else "were",
|
534 |
+
)
|
535 |
+
warnings.warn(msg, RuntimeWarning, stacklevel=2)
|
536 |
+
|
537 |
+
return svmem(
|
538 |
+
total,
|
539 |
+
avail,
|
540 |
+
percent,
|
541 |
+
used,
|
542 |
+
free,
|
543 |
+
active,
|
544 |
+
inactive,
|
545 |
+
buffers,
|
546 |
+
cached,
|
547 |
+
shared,
|
548 |
+
slab,
|
549 |
+
)
|
550 |
+
|
551 |
+
|
552 |
+
def swap_memory():
|
553 |
+
"""Return swap memory metrics."""
|
554 |
+
mems = {}
|
555 |
+
with open_binary('%s/meminfo' % get_procfs_path()) as f:
|
556 |
+
for line in f:
|
557 |
+
fields = line.split()
|
558 |
+
mems[fields[0]] = int(fields[1]) * 1024
|
559 |
+
# We prefer /proc/meminfo over sysinfo() syscall so that
|
560 |
+
# psutil.PROCFS_PATH can be used in order to allow retrieval
|
561 |
+
# for linux containers, see:
|
562 |
+
# https://github.com/giampaolo/psutil/issues/1015
|
563 |
+
try:
|
564 |
+
total = mems[b'SwapTotal:']
|
565 |
+
free = mems[b'SwapFree:']
|
566 |
+
except KeyError:
|
567 |
+
_, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
|
568 |
+
total *= unit_multiplier
|
569 |
+
free *= unit_multiplier
|
570 |
+
|
571 |
+
used = total - free
|
572 |
+
percent = usage_percent(used, total, round_=1)
|
573 |
+
# get pgin/pgouts
|
574 |
+
try:
|
575 |
+
f = open_binary("%s/vmstat" % get_procfs_path())
|
576 |
+
except IOError as err:
|
577 |
+
# see https://github.com/giampaolo/psutil/issues/722
|
578 |
+
msg = (
|
579 |
+
"'sin' and 'sout' swap memory stats couldn't "
|
580 |
+
+ "be determined and were set to 0 (%s)" % str(err)
|
581 |
+
)
|
582 |
+
warnings.warn(msg, RuntimeWarning, stacklevel=2)
|
583 |
+
sin = sout = 0
|
584 |
+
else:
|
585 |
+
with f:
|
586 |
+
sin = sout = None
|
587 |
+
for line in f:
|
588 |
+
# values are expressed in 4 kilo bytes, we want
|
589 |
+
# bytes instead
|
590 |
+
if line.startswith(b'pswpin'):
|
591 |
+
sin = int(line.split(b' ')[1]) * 4 * 1024
|
592 |
+
elif line.startswith(b'pswpout'):
|
593 |
+
sout = int(line.split(b' ')[1]) * 4 * 1024
|
594 |
+
if sin is not None and sout is not None:
|
595 |
+
break
|
596 |
+
else:
|
597 |
+
# we might get here when dealing with exotic Linux
|
598 |
+
# flavors, see:
|
599 |
+
# https://github.com/giampaolo/psutil/issues/313
|
600 |
+
msg = "'sin' and 'sout' swap memory stats couldn't "
|
601 |
+
msg += "be determined and were set to 0"
|
602 |
+
warnings.warn(msg, RuntimeWarning, stacklevel=2)
|
603 |
+
sin = sout = 0
|
604 |
+
return _common.sswap(total, used, free, percent, sin, sout)
|
605 |
+
|
606 |
+
|
607 |
+
# =====================================================================
|
608 |
+
# --- CPU
|
609 |
+
# =====================================================================
|
610 |
+
|
611 |
+
|
612 |
+
def cpu_times():
|
613 |
+
"""Return a named tuple representing the following system-wide
|
614 |
+
CPU times:
|
615 |
+
(user, nice, system, idle, iowait, irq, softirq [steal, [guest,
|
616 |
+
[guest_nice]]])
|
617 |
+
Last 3 fields may not be available on all Linux kernel versions.
|
618 |
+
"""
|
619 |
+
procfs_path = get_procfs_path()
|
620 |
+
set_scputimes_ntuple(procfs_path)
|
621 |
+
with open_binary('%s/stat' % procfs_path) as f:
|
622 |
+
values = f.readline().split()
|
623 |
+
fields = values[1 : len(scputimes._fields) + 1]
|
624 |
+
fields = [float(x) / CLOCK_TICKS for x in fields]
|
625 |
+
return scputimes(*fields)
|
626 |
+
|
627 |
+
|
628 |
+
def per_cpu_times():
|
629 |
+
"""Return a list of namedtuple representing the CPU times
|
630 |
+
for every CPU available on the system.
|
631 |
+
"""
|
632 |
+
procfs_path = get_procfs_path()
|
633 |
+
set_scputimes_ntuple(procfs_path)
|
634 |
+
cpus = []
|
635 |
+
with open_binary('%s/stat' % procfs_path) as f:
|
636 |
+
# get rid of the first line which refers to system wide CPU stats
|
637 |
+
f.readline()
|
638 |
+
for line in f:
|
639 |
+
if line.startswith(b'cpu'):
|
640 |
+
values = line.split()
|
641 |
+
fields = values[1 : len(scputimes._fields) + 1]
|
642 |
+
fields = [float(x) / CLOCK_TICKS for x in fields]
|
643 |
+
entry = scputimes(*fields)
|
644 |
+
cpus.append(entry)
|
645 |
+
return cpus
|
646 |
+
|
647 |
+
|
648 |
+
def cpu_count_logical():
|
649 |
+
"""Return the number of logical CPUs in the system."""
|
650 |
+
try:
|
651 |
+
return os.sysconf("SC_NPROCESSORS_ONLN")
|
652 |
+
except ValueError:
|
653 |
+
# as a second fallback we try to parse /proc/cpuinfo
|
654 |
+
num = 0
|
655 |
+
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
|
656 |
+
for line in f:
|
657 |
+
if line.lower().startswith(b'processor'):
|
658 |
+
num += 1
|
659 |
+
|
660 |
+
# unknown format (e.g. amrel/sparc architectures), see:
|
661 |
+
# https://github.com/giampaolo/psutil/issues/200
|
662 |
+
# try to parse /proc/stat as a last resort
|
663 |
+
if num == 0:
|
664 |
+
search = re.compile(r'cpu\d')
|
665 |
+
with open_text('%s/stat' % get_procfs_path()) as f:
|
666 |
+
for line in f:
|
667 |
+
line = line.split(' ')[0]
|
668 |
+
if search.match(line):
|
669 |
+
num += 1
|
670 |
+
|
671 |
+
if num == 0:
|
672 |
+
# mimic os.cpu_count()
|
673 |
+
return None
|
674 |
+
return num
|
675 |
+
|
676 |
+
|
677 |
+
def cpu_count_cores():
|
678 |
+
"""Return the number of CPU cores in the system."""
|
679 |
+
# Method #1
|
680 |
+
ls = set()
|
681 |
+
# These 2 files are the same but */core_cpus_list is newer while
|
682 |
+
# */thread_siblings_list is deprecated and may disappear in the future.
|
683 |
+
# https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst
|
684 |
+
# https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964
|
685 |
+
# https://lkml.org/lkml/2019/2/26/41
|
686 |
+
p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list"
|
687 |
+
p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"
|
688 |
+
for path in glob.glob(p1) or glob.glob(p2):
|
689 |
+
with open_binary(path) as f:
|
690 |
+
ls.add(f.read().strip())
|
691 |
+
result = len(ls)
|
692 |
+
if result != 0:
|
693 |
+
return result
|
694 |
+
|
695 |
+
# Method #2
|
696 |
+
mapping = {}
|
697 |
+
current_info = {}
|
698 |
+
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
|
699 |
+
for line in f:
|
700 |
+
line = line.strip().lower()
|
701 |
+
if not line:
|
702 |
+
# new section
|
703 |
+
try:
|
704 |
+
mapping[current_info[b'physical id']] = current_info[
|
705 |
+
b'cpu cores'
|
706 |
+
]
|
707 |
+
except KeyError:
|
708 |
+
pass
|
709 |
+
current_info = {}
|
710 |
+
else:
|
711 |
+
# ongoing section
|
712 |
+
if line.startswith((b'physical id', b'cpu cores')):
|
713 |
+
key, value = line.split(b'\t:', 1)
|
714 |
+
current_info[key] = int(value)
|
715 |
+
|
716 |
+
result = sum(mapping.values())
|
717 |
+
return result or None # mimic os.cpu_count()
|
718 |
+
|
719 |
+
|
720 |
+
def cpu_stats():
|
721 |
+
"""Return various CPU stats as a named tuple."""
|
722 |
+
with open_binary('%s/stat' % get_procfs_path()) as f:
|
723 |
+
ctx_switches = None
|
724 |
+
interrupts = None
|
725 |
+
soft_interrupts = None
|
726 |
+
for line in f:
|
727 |
+
if line.startswith(b'ctxt'):
|
728 |
+
ctx_switches = int(line.split()[1])
|
729 |
+
elif line.startswith(b'intr'):
|
730 |
+
interrupts = int(line.split()[1])
|
731 |
+
elif line.startswith(b'softirq'):
|
732 |
+
soft_interrupts = int(line.split()[1])
|
733 |
+
if (
|
734 |
+
ctx_switches is not None
|
735 |
+
and soft_interrupts is not None
|
736 |
+
and interrupts is not None
|
737 |
+
):
|
738 |
+
break
|
739 |
+
syscalls = 0
|
740 |
+
return _common.scpustats(
|
741 |
+
ctx_switches, interrupts, soft_interrupts, syscalls
|
742 |
+
)
|
743 |
+
|
744 |
+
|
745 |
+
def _cpu_get_cpuinfo_freq():
|
746 |
+
"""Return current CPU frequency from cpuinfo if available."""
|
747 |
+
ret = []
|
748 |
+
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
|
749 |
+
for line in f:
|
750 |
+
if line.lower().startswith(b'cpu mhz'):
|
751 |
+
ret.append(float(line.split(b':', 1)[1]))
|
752 |
+
return ret
|
753 |
+
|
754 |
+
|
755 |
+
if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or os.path.exists(
|
756 |
+
"/sys/devices/system/cpu/cpu0/cpufreq"
|
757 |
+
):
|
758 |
+
|
759 |
+
def cpu_freq():
|
760 |
+
"""Return frequency metrics for all CPUs.
|
761 |
+
Contrarily to other OSes, Linux updates these values in
|
762 |
+
real-time.
|
763 |
+
"""
|
764 |
+
cpuinfo_freqs = _cpu_get_cpuinfo_freq()
|
765 |
+
paths = glob.glob(
|
766 |
+
"/sys/devices/system/cpu/cpufreq/policy[0-9]*"
|
767 |
+
) or glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq")
|
768 |
+
paths.sort(key=lambda x: int(re.search(r"[0-9]+", x).group()))
|
769 |
+
ret = []
|
770 |
+
pjoin = os.path.join
|
771 |
+
for i, path in enumerate(paths):
|
772 |
+
if len(paths) == len(cpuinfo_freqs):
|
773 |
+
# take cached value from cpuinfo if available, see:
|
774 |
+
# https://github.com/giampaolo/psutil/issues/1851
|
775 |
+
curr = cpuinfo_freqs[i] * 1000
|
776 |
+
else:
|
777 |
+
curr = bcat(pjoin(path, "scaling_cur_freq"), fallback=None)
|
778 |
+
if curr is None:
|
779 |
+
# Likely an old RedHat, see:
|
780 |
+
# https://github.com/giampaolo/psutil/issues/1071
|
781 |
+
curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
|
782 |
+
if curr is None:
|
783 |
+
msg = "can't find current frequency file"
|
784 |
+
raise NotImplementedError(msg)
|
785 |
+
curr = int(curr) / 1000
|
786 |
+
max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000
|
787 |
+
min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000
|
788 |
+
ret.append(_common.scpufreq(curr, min_, max_))
|
789 |
+
return ret
|
790 |
+
|
791 |
+
else:
|
792 |
+
|
793 |
+
def cpu_freq():
|
794 |
+
"""Alternate implementation using /proc/cpuinfo.
|
795 |
+
min and max frequencies are not available and are set to None.
|
796 |
+
"""
|
797 |
+
return [_common.scpufreq(x, 0.0, 0.0) for x in _cpu_get_cpuinfo_freq()]
|
798 |
+
|
799 |
+
|
800 |
+
# =====================================================================
|
801 |
+
# --- network
|
802 |
+
# =====================================================================
|
803 |
+
|
804 |
+
|
805 |
+
net_if_addrs = cext_posix.net_if_addrs
|
806 |
+
|
807 |
+
|
808 |
+
class _Ipv6UnsupportedError(Exception):
|
809 |
+
pass
|
810 |
+
|
811 |
+
|
812 |
+
class Connections:
|
813 |
+
"""A wrapper on top of /proc/net/* files, retrieving per-process
|
814 |
+
and system-wide open connections (TCP, UDP, UNIX) similarly to
|
815 |
+
"netstat -an".
|
816 |
+
|
817 |
+
Note: in case of UNIX sockets we're only able to determine the
|
818 |
+
local endpoint/path, not the one it's connected to.
|
819 |
+
According to [1] it would be possible but not easily.
|
820 |
+
|
821 |
+
[1] http://serverfault.com/a/417946
|
822 |
+
"""
|
823 |
+
|
824 |
+
def __init__(self):
|
825 |
+
# The string represents the basename of the corresponding
|
826 |
+
# /proc/net/{proto_name} file.
|
827 |
+
tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
|
828 |
+
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
|
829 |
+
udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
|
830 |
+
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
|
831 |
+
unix = ("unix", socket.AF_UNIX, None)
|
832 |
+
self.tmap = {
|
833 |
+
"all": (tcp4, tcp6, udp4, udp6, unix),
|
834 |
+
"tcp": (tcp4, tcp6),
|
835 |
+
"tcp4": (tcp4,),
|
836 |
+
"tcp6": (tcp6,),
|
837 |
+
"udp": (udp4, udp6),
|
838 |
+
"udp4": (udp4,),
|
839 |
+
"udp6": (udp6,),
|
840 |
+
"unix": (unix,),
|
841 |
+
"inet": (tcp4, tcp6, udp4, udp6),
|
842 |
+
"inet4": (tcp4, udp4),
|
843 |
+
"inet6": (tcp6, udp6),
|
844 |
+
}
|
845 |
+
self._procfs_path = None
|
846 |
+
|
847 |
+
def get_proc_inodes(self, pid):
|
848 |
+
inodes = defaultdict(list)
|
849 |
+
for fd in os.listdir("%s/%s/fd" % (self._procfs_path, pid)):
|
850 |
+
try:
|
851 |
+
inode = readlink("%s/%s/fd/%s" % (self._procfs_path, pid, fd))
|
852 |
+
except (FileNotFoundError, ProcessLookupError):
|
853 |
+
# ENOENT == file which is gone in the meantime;
|
854 |
+
# os.stat('/proc/%s' % self.pid) will be done later
|
855 |
+
# to force NSP (if it's the case)
|
856 |
+
continue
|
857 |
+
except OSError as err:
|
858 |
+
if err.errno == errno.EINVAL:
|
859 |
+
# not a link
|
860 |
+
continue
|
861 |
+
if err.errno == errno.ENAMETOOLONG:
|
862 |
+
# file name too long
|
863 |
+
debug(err)
|
864 |
+
continue
|
865 |
+
raise
|
866 |
+
else:
|
867 |
+
if inode.startswith('socket:['):
|
868 |
+
# the process is using a socket
|
869 |
+
inode = inode[8:][:-1]
|
870 |
+
inodes[inode].append((pid, int(fd)))
|
871 |
+
return inodes
|
872 |
+
|
873 |
+
def get_all_inodes(self):
|
874 |
+
inodes = {}
|
875 |
+
for pid in pids():
|
876 |
+
try:
|
877 |
+
inodes.update(self.get_proc_inodes(pid))
|
878 |
+
except (FileNotFoundError, ProcessLookupError, PermissionError):
|
879 |
+
# os.listdir() is gonna raise a lot of access denied
|
880 |
+
# exceptions in case of unprivileged user; that's fine
|
881 |
+
# as we'll just end up returning a connection with PID
|
882 |
+
# and fd set to None anyway.
|
883 |
+
# Both netstat -an and lsof does the same so it's
|
884 |
+
# unlikely we can do any better.
|
885 |
+
# ENOENT just means a PID disappeared on us.
|
886 |
+
continue
|
887 |
+
return inodes
|
888 |
+
|
889 |
+
@staticmethod
|
890 |
+
def decode_address(addr, family):
|
891 |
+
"""Accept an "ip:port" address as displayed in /proc/net/*
|
892 |
+
and convert it into a human readable form, like:
|
893 |
+
|
894 |
+
"0500000A:0016" -> ("10.0.0.5", 22)
|
895 |
+
"0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
|
896 |
+
|
897 |
+
The IP address portion is a little or big endian four-byte
|
898 |
+
hexadecimal number; that is, the least significant byte is listed
|
899 |
+
first, so we need to reverse the order of the bytes to convert it
|
900 |
+
to an IP address.
|
901 |
+
The port is represented as a two-byte hexadecimal number.
|
902 |
+
|
903 |
+
Reference:
|
904 |
+
http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
|
905 |
+
"""
|
906 |
+
ip, port = addr.split(':')
|
907 |
+
port = int(port, 16)
|
908 |
+
# this usually refers to a local socket in listen mode with
|
909 |
+
# no end-points connected
|
910 |
+
if not port:
|
911 |
+
return ()
|
912 |
+
if PY3:
|
913 |
+
ip = ip.encode('ascii')
|
914 |
+
if family == socket.AF_INET:
|
915 |
+
# see: https://github.com/giampaolo/psutil/issues/201
|
916 |
+
if LITTLE_ENDIAN:
|
917 |
+
ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
|
918 |
+
else:
|
919 |
+
ip = socket.inet_ntop(family, base64.b16decode(ip))
|
920 |
+
else: # IPv6
|
921 |
+
ip = base64.b16decode(ip)
|
922 |
+
try:
|
923 |
+
# see: https://github.com/giampaolo/psutil/issues/201
|
924 |
+
if LITTLE_ENDIAN:
|
925 |
+
ip = socket.inet_ntop(
|
926 |
+
socket.AF_INET6,
|
927 |
+
struct.pack('>4I', *struct.unpack('<4I', ip)),
|
928 |
+
)
|
929 |
+
else:
|
930 |
+
ip = socket.inet_ntop(
|
931 |
+
socket.AF_INET6,
|
932 |
+
struct.pack('<4I', *struct.unpack('<4I', ip)),
|
933 |
+
)
|
934 |
+
except ValueError:
|
935 |
+
# see: https://github.com/giampaolo/psutil/issues/623
|
936 |
+
if not supports_ipv6():
|
937 |
+
raise _Ipv6UnsupportedError
|
938 |
+
else:
|
939 |
+
raise
|
940 |
+
return _common.addr(ip, port)
|
941 |
+
|
942 |
+
@staticmethod
|
943 |
+
def process_inet(file, family, type_, inodes, filter_pid=None):
|
944 |
+
"""Parse /proc/net/tcp* and /proc/net/udp* files."""
|
945 |
+
if file.endswith('6') and not os.path.exists(file):
|
946 |
+
# IPv6 not supported
|
947 |
+
return
|
948 |
+
with open_text(file) as f:
|
949 |
+
f.readline() # skip the first line
|
950 |
+
for lineno, line in enumerate(f, 1):
|
951 |
+
try:
|
952 |
+
_, laddr, raddr, status, _, _, _, _, _, inode = (
|
953 |
+
line.split()[:10]
|
954 |
+
)
|
955 |
+
except ValueError:
|
956 |
+
raise RuntimeError(
|
957 |
+
"error while parsing %s; malformed line %s %r"
|
958 |
+
% (file, lineno, line)
|
959 |
+
)
|
960 |
+
if inode in inodes:
|
961 |
+
# # We assume inet sockets are unique, so we error
|
962 |
+
# # out if there are multiple references to the
|
963 |
+
# # same inode. We won't do this for UNIX sockets.
|
964 |
+
# if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
|
965 |
+
# raise ValueError("ambiguous inode with multiple "
|
966 |
+
# "PIDs references")
|
967 |
+
pid, fd = inodes[inode][0]
|
968 |
+
else:
|
969 |
+
pid, fd = None, -1
|
970 |
+
if filter_pid is not None and filter_pid != pid:
|
971 |
+
continue
|
972 |
+
else:
|
973 |
+
if type_ == socket.SOCK_STREAM:
|
974 |
+
status = TCP_STATUSES[status]
|
975 |
+
else:
|
976 |
+
status = _common.CONN_NONE
|
977 |
+
try:
|
978 |
+
laddr = Connections.decode_address(laddr, family)
|
979 |
+
raddr = Connections.decode_address(raddr, family)
|
980 |
+
except _Ipv6UnsupportedError:
|
981 |
+
continue
|
982 |
+
yield (fd, family, type_, laddr, raddr, status, pid)
|
983 |
+
|
984 |
+
@staticmethod
|
985 |
+
def process_unix(file, family, inodes, filter_pid=None):
|
986 |
+
"""Parse /proc/net/unix files."""
|
987 |
+
with open_text(file) as f:
|
988 |
+
f.readline() # skip the first line
|
989 |
+
for line in f:
|
990 |
+
tokens = line.split()
|
991 |
+
try:
|
992 |
+
_, _, _, _, type_, _, inode = tokens[0:7]
|
993 |
+
except ValueError:
|
994 |
+
if ' ' not in line:
|
995 |
+
# see: https://github.com/giampaolo/psutil/issues/766
|
996 |
+
continue
|
997 |
+
raise RuntimeError(
|
998 |
+
"error while parsing %s; malformed line %r"
|
999 |
+
% (file, line)
|
1000 |
+
)
|
1001 |
+
if inode in inodes: # noqa
|
1002 |
+
# With UNIX sockets we can have a single inode
|
1003 |
+
# referencing many file descriptors.
|
1004 |
+
pairs = inodes[inode]
|
1005 |
+
else:
|
1006 |
+
pairs = [(None, -1)]
|
1007 |
+
for pid, fd in pairs:
|
1008 |
+
if filter_pid is not None and filter_pid != pid:
|
1009 |
+
continue
|
1010 |
+
else:
|
1011 |
+
path = tokens[-1] if len(tokens) == 8 else ''
|
1012 |
+
type_ = _common.socktype_to_enum(int(type_))
|
1013 |
+
# XXX: determining the remote endpoint of a
|
1014 |
+
# UNIX socket on Linux is not possible, see:
|
1015 |
+
# https://serverfault.com/questions/252723/
|
1016 |
+
raddr = ""
|
1017 |
+
status = _common.CONN_NONE
|
1018 |
+
yield (fd, family, type_, path, raddr, status, pid)
|
1019 |
+
|
1020 |
+
def retrieve(self, kind, pid=None):
|
1021 |
+
if kind not in self.tmap:
|
1022 |
+
raise ValueError(
|
1023 |
+
"invalid %r kind argument; choose between %s"
|
1024 |
+
% (kind, ', '.join([repr(x) for x in self.tmap]))
|
1025 |
+
)
|
1026 |
+
self._procfs_path = get_procfs_path()
|
1027 |
+
if pid is not None:
|
1028 |
+
inodes = self.get_proc_inodes(pid)
|
1029 |
+
if not inodes:
|
1030 |
+
# no connections for this process
|
1031 |
+
return []
|
1032 |
+
else:
|
1033 |
+
inodes = self.get_all_inodes()
|
1034 |
+
ret = set()
|
1035 |
+
for proto_name, family, type_ in self.tmap[kind]:
|
1036 |
+
path = "%s/net/%s" % (self._procfs_path, proto_name)
|
1037 |
+
if family in (socket.AF_INET, socket.AF_INET6):
|
1038 |
+
ls = self.process_inet(
|
1039 |
+
path, family, type_, inodes, filter_pid=pid
|
1040 |
+
)
|
1041 |
+
else:
|
1042 |
+
ls = self.process_unix(path, family, inodes, filter_pid=pid)
|
1043 |
+
for fd, family, type_, laddr, raddr, status, bound_pid in ls:
|
1044 |
+
if pid:
|
1045 |
+
conn = _common.pconn(
|
1046 |
+
fd, family, type_, laddr, raddr, status
|
1047 |
+
)
|
1048 |
+
else:
|
1049 |
+
conn = _common.sconn(
|
1050 |
+
fd, family, type_, laddr, raddr, status, bound_pid
|
1051 |
+
)
|
1052 |
+
ret.add(conn)
|
1053 |
+
return list(ret)
|
1054 |
+
|
1055 |
+
|
1056 |
+
_connections = Connections()
|
1057 |
+
|
1058 |
+
|
1059 |
+
def net_connections(kind='inet'):
|
1060 |
+
"""Return system-wide open connections."""
|
1061 |
+
return _connections.retrieve(kind)
|
1062 |
+
|
1063 |
+
|
1064 |
+
def net_io_counters():
|
1065 |
+
"""Return network I/O statistics for every network interface
|
1066 |
+
installed on the system as a dict of raw tuples.
|
1067 |
+
"""
|
1068 |
+
with open_text("%s/net/dev" % get_procfs_path()) as f:
|
1069 |
+
lines = f.readlines()
|
1070 |
+
retdict = {}
|
1071 |
+
for line in lines[2:]:
|
1072 |
+
colon = line.rfind(':')
|
1073 |
+
assert colon > 0, repr(line)
|
1074 |
+
name = line[:colon].strip()
|
1075 |
+
fields = line[colon + 1 :].strip().split()
|
1076 |
+
|
1077 |
+
# in
|
1078 |
+
(
|
1079 |
+
bytes_recv,
|
1080 |
+
packets_recv,
|
1081 |
+
errin,
|
1082 |
+
dropin,
|
1083 |
+
fifoin, # unused
|
1084 |
+
framein, # unused
|
1085 |
+
compressedin, # unused
|
1086 |
+
multicastin, # unused
|
1087 |
+
# out
|
1088 |
+
bytes_sent,
|
1089 |
+
packets_sent,
|
1090 |
+
errout,
|
1091 |
+
dropout,
|
1092 |
+
fifoout, # unused
|
1093 |
+
collisionsout, # unused
|
1094 |
+
carrierout, # unused
|
1095 |
+
compressedout,
|
1096 |
+
) = map(int, fields)
|
1097 |
+
|
1098 |
+
retdict[name] = (
|
1099 |
+
bytes_sent,
|
1100 |
+
bytes_recv,
|
1101 |
+
packets_sent,
|
1102 |
+
packets_recv,
|
1103 |
+
errin,
|
1104 |
+
errout,
|
1105 |
+
dropin,
|
1106 |
+
dropout,
|
1107 |
+
)
|
1108 |
+
return retdict
|
1109 |
+
|
1110 |
+
|
1111 |
+
def net_if_stats():
|
1112 |
+
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
1113 |
+
duplex_map = {
|
1114 |
+
cext.DUPLEX_FULL: NIC_DUPLEX_FULL,
|
1115 |
+
cext.DUPLEX_HALF: NIC_DUPLEX_HALF,
|
1116 |
+
cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN,
|
1117 |
+
}
|
1118 |
+
names = net_io_counters().keys()
|
1119 |
+
ret = {}
|
1120 |
+
for name in names:
|
1121 |
+
try:
|
1122 |
+
mtu = cext_posix.net_if_mtu(name)
|
1123 |
+
flags = cext_posix.net_if_flags(name)
|
1124 |
+
duplex, speed = cext.net_if_duplex_speed(name)
|
1125 |
+
except OSError as err:
|
1126 |
+
# https://github.com/giampaolo/psutil/issues/1279
|
1127 |
+
if err.errno != errno.ENODEV:
|
1128 |
+
raise
|
1129 |
+
else:
|
1130 |
+
debug(err)
|
1131 |
+
else:
|
1132 |
+
output_flags = ','.join(flags)
|
1133 |
+
isup = 'running' in flags
|
1134 |
+
ret[name] = _common.snicstats(
|
1135 |
+
isup, duplex_map[duplex], speed, mtu, output_flags
|
1136 |
+
)
|
1137 |
+
return ret
|
1138 |
+
|
1139 |
+
|
1140 |
+
# =====================================================================
|
1141 |
+
# --- disks
|
1142 |
+
# =====================================================================
|
1143 |
+
|
1144 |
+
|
1145 |
+
disk_usage = _psposix.disk_usage
|
1146 |
+
|
1147 |
+
|
1148 |
+
def disk_io_counters(perdisk=False):
|
1149 |
+
"""Return disk I/O statistics for every disk installed on the
|
1150 |
+
system as a dict of raw tuples.
|
1151 |
+
"""
|
1152 |
+
|
1153 |
+
def read_procfs():
|
1154 |
+
# OK, this is a bit confusing. The format of /proc/diskstats can
|
1155 |
+
# have 3 variations.
|
1156 |
+
# On Linux 2.4 each line has always 15 fields, e.g.:
|
1157 |
+
# "3 0 8 hda 8 8 8 8 8 8 8 8 8 8 8"
|
1158 |
+
# On Linux 2.6+ each line *usually* has 14 fields, and the disk
|
1159 |
+
# name is in another position, like this:
|
1160 |
+
# "3 0 hda 8 8 8 8 8 8 8 8 8 8 8"
|
1161 |
+
# ...unless (Linux 2.6) the line refers to a partition instead
|
1162 |
+
# of a disk, in which case the line has less fields (7):
|
1163 |
+
# "3 1 hda1 8 8 8 8"
|
1164 |
+
# 4.18+ has 4 fields added:
|
1165 |
+
# "3 0 hda 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0"
|
1166 |
+
# 5.5 has 2 more fields.
|
1167 |
+
# See:
|
1168 |
+
# https://www.kernel.org/doc/Documentation/iostats.txt
|
1169 |
+
# https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
|
1170 |
+
with open_text("%s/diskstats" % get_procfs_path()) as f:
|
1171 |
+
lines = f.readlines()
|
1172 |
+
for line in lines:
|
1173 |
+
fields = line.split()
|
1174 |
+
flen = len(fields)
|
1175 |
+
# fmt: off
|
1176 |
+
if flen == 15:
|
1177 |
+
# Linux 2.4
|
1178 |
+
name = fields[3]
|
1179 |
+
reads = int(fields[2])
|
1180 |
+
(reads_merged, rbytes, rtime, writes, writes_merged,
|
1181 |
+
wbytes, wtime, _, busy_time, _) = map(int, fields[4:14])
|
1182 |
+
elif flen == 14 or flen >= 18:
|
1183 |
+
# Linux 2.6+, line referring to a disk
|
1184 |
+
name = fields[2]
|
1185 |
+
(reads, reads_merged, rbytes, rtime, writes, writes_merged,
|
1186 |
+
wbytes, wtime, _, busy_time, _) = map(int, fields[3:14])
|
1187 |
+
elif flen == 7:
|
1188 |
+
# Linux 2.6+, line referring to a partition
|
1189 |
+
name = fields[2]
|
1190 |
+
reads, rbytes, writes, wbytes = map(int, fields[3:])
|
1191 |
+
rtime = wtime = reads_merged = writes_merged = busy_time = 0
|
1192 |
+
else:
|
1193 |
+
raise ValueError("not sure how to interpret line %r" % line)
|
1194 |
+
yield (name, reads, writes, rbytes, wbytes, rtime, wtime,
|
1195 |
+
reads_merged, writes_merged, busy_time)
|
1196 |
+
# fmt: on
|
1197 |
+
|
1198 |
+
def read_sysfs():
|
1199 |
+
for block in os.listdir('/sys/block'):
|
1200 |
+
for root, _, files in os.walk(os.path.join('/sys/block', block)):
|
1201 |
+
if 'stat' not in files:
|
1202 |
+
continue
|
1203 |
+
with open_text(os.path.join(root, 'stat')) as f:
|
1204 |
+
fields = f.read().strip().split()
|
1205 |
+
name = os.path.basename(root)
|
1206 |
+
# fmt: off
|
1207 |
+
(reads, reads_merged, rbytes, rtime, writes, writes_merged,
|
1208 |
+
wbytes, wtime, _, busy_time) = map(int, fields[:10])
|
1209 |
+
yield (name, reads, writes, rbytes, wbytes, rtime,
|
1210 |
+
wtime, reads_merged, writes_merged, busy_time)
|
1211 |
+
# fmt: on
|
1212 |
+
|
1213 |
+
if os.path.exists('%s/diskstats' % get_procfs_path()):
|
1214 |
+
gen = read_procfs()
|
1215 |
+
elif os.path.exists('/sys/block'):
|
1216 |
+
gen = read_sysfs()
|
1217 |
+
else:
|
1218 |
+
raise NotImplementedError(
|
1219 |
+
"%s/diskstats nor /sys/block filesystem are available on this "
|
1220 |
+
"system"
|
1221 |
+
% get_procfs_path()
|
1222 |
+
)
|
1223 |
+
|
1224 |
+
retdict = {}
|
1225 |
+
for entry in gen:
|
1226 |
+
# fmt: off
|
1227 |
+
(name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged,
|
1228 |
+
writes_merged, busy_time) = entry
|
1229 |
+
if not perdisk and not is_storage_device(name):
|
1230 |
+
# perdisk=False means we want to calculate totals so we skip
|
1231 |
+
# partitions (e.g. 'sda1', 'nvme0n1p1') and only include
|
1232 |
+
# base disk devices (e.g. 'sda', 'nvme0n1'). Base disks
|
1233 |
+
# include a total of all their partitions + some extra size
|
1234 |
+
# of their own:
|
1235 |
+
# $ cat /proc/diskstats
|
1236 |
+
# 259 0 sda 10485760 ...
|
1237 |
+
# 259 1 sda1 5186039 ...
|
1238 |
+
# 259 1 sda2 5082039 ...
|
1239 |
+
# See:
|
1240 |
+
# https://github.com/giampaolo/psutil/pull/1313
|
1241 |
+
continue
|
1242 |
+
|
1243 |
+
rbytes *= DISK_SECTOR_SIZE
|
1244 |
+
wbytes *= DISK_SECTOR_SIZE
|
1245 |
+
retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime,
|
1246 |
+
reads_merged, writes_merged, busy_time)
|
1247 |
+
# fmt: on
|
1248 |
+
|
1249 |
+
return retdict
|
1250 |
+
|
1251 |
+
|
1252 |
+
class RootFsDeviceFinder:
|
1253 |
+
"""disk_partitions() may return partitions with device == "/dev/root"
|
1254 |
+
or "rootfs". This container class uses different strategies to try to
|
1255 |
+
obtain the real device path. Resources:
|
1256 |
+
https://bootlin.com/blog/find-root-device/
|
1257 |
+
https://www.systutorials.com/how-to-find-the-disk-where-root-is-on-in-bash-on-linux/.
|
1258 |
+
"""
|
1259 |
+
|
1260 |
+
__slots__ = ['major', 'minor']
|
1261 |
+
|
1262 |
+
def __init__(self):
|
1263 |
+
dev = os.stat("/").st_dev
|
1264 |
+
self.major = os.major(dev)
|
1265 |
+
self.minor = os.minor(dev)
|
1266 |
+
|
1267 |
+
def ask_proc_partitions(self):
|
1268 |
+
with open_text("%s/partitions" % get_procfs_path()) as f:
|
1269 |
+
for line in f.readlines()[2:]:
|
1270 |
+
fields = line.split()
|
1271 |
+
if len(fields) < 4: # just for extra safety
|
1272 |
+
continue
|
1273 |
+
major = int(fields[0]) if fields[0].isdigit() else None
|
1274 |
+
minor = int(fields[1]) if fields[1].isdigit() else None
|
1275 |
+
name = fields[3]
|
1276 |
+
if major == self.major and minor == self.minor:
|
1277 |
+
if name: # just for extra safety
|
1278 |
+
return "/dev/%s" % name
|
1279 |
+
|
1280 |
+
def ask_sys_dev_block(self):
|
1281 |
+
path = "/sys/dev/block/%s:%s/uevent" % (self.major, self.minor)
|
1282 |
+
with open_text(path) as f:
|
1283 |
+
for line in f:
|
1284 |
+
if line.startswith("DEVNAME="):
|
1285 |
+
name = line.strip().rpartition("DEVNAME=")[2]
|
1286 |
+
if name: # just for extra safety
|
1287 |
+
return "/dev/%s" % name
|
1288 |
+
|
1289 |
+
def ask_sys_class_block(self):
|
1290 |
+
needle = "%s:%s" % (self.major, self.minor)
|
1291 |
+
files = glob.iglob("/sys/class/block/*/dev")
|
1292 |
+
for file in files:
|
1293 |
+
try:
|
1294 |
+
f = open_text(file)
|
1295 |
+
except FileNotFoundError: # race condition
|
1296 |
+
continue
|
1297 |
+
else:
|
1298 |
+
with f:
|
1299 |
+
data = f.read().strip()
|
1300 |
+
if data == needle:
|
1301 |
+
name = os.path.basename(os.path.dirname(file))
|
1302 |
+
return "/dev/%s" % name
|
1303 |
+
|
1304 |
+
def find(self):
|
1305 |
+
path = None
|
1306 |
+
if path is None:
|
1307 |
+
try:
|
1308 |
+
path = self.ask_proc_partitions()
|
1309 |
+
except (IOError, OSError) as err:
|
1310 |
+
debug(err)
|
1311 |
+
if path is None:
|
1312 |
+
try:
|
1313 |
+
path = self.ask_sys_dev_block()
|
1314 |
+
except (IOError, OSError) as err:
|
1315 |
+
debug(err)
|
1316 |
+
if path is None:
|
1317 |
+
try:
|
1318 |
+
path = self.ask_sys_class_block()
|
1319 |
+
except (IOError, OSError) as err:
|
1320 |
+
debug(err)
|
1321 |
+
# We use exists() because the "/dev/*" part of the path is hard
|
1322 |
+
# coded, so we want to be sure.
|
1323 |
+
if path is not None and os.path.exists(path):
|
1324 |
+
return path
|
1325 |
+
|
1326 |
+
|
1327 |
+
def disk_partitions(all=False):
|
1328 |
+
"""Return mounted disk partitions as a list of namedtuples."""
|
1329 |
+
fstypes = set()
|
1330 |
+
procfs_path = get_procfs_path()
|
1331 |
+
if not all:
|
1332 |
+
with open_text("%s/filesystems" % procfs_path) as f:
|
1333 |
+
for line in f:
|
1334 |
+
line = line.strip()
|
1335 |
+
if not line.startswith("nodev"):
|
1336 |
+
fstypes.add(line.strip())
|
1337 |
+
else:
|
1338 |
+
# ignore all lines starting with "nodev" except "nodev zfs"
|
1339 |
+
fstype = line.split("\t")[1]
|
1340 |
+
if fstype == "zfs":
|
1341 |
+
fstypes.add("zfs")
|
1342 |
+
|
1343 |
+
# See: https://github.com/giampaolo/psutil/issues/1307
|
1344 |
+
if procfs_path == "/proc" and os.path.isfile('/etc/mtab'):
|
1345 |
+
mounts_path = os.path.realpath("/etc/mtab")
|
1346 |
+
else:
|
1347 |
+
mounts_path = os.path.realpath("%s/self/mounts" % procfs_path)
|
1348 |
+
|
1349 |
+
retlist = []
|
1350 |
+
partitions = cext.disk_partitions(mounts_path)
|
1351 |
+
for partition in partitions:
|
1352 |
+
device, mountpoint, fstype, opts = partition
|
1353 |
+
if device == 'none':
|
1354 |
+
device = ''
|
1355 |
+
if device in ("/dev/root", "rootfs"):
|
1356 |
+
device = RootFsDeviceFinder().find() or device
|
1357 |
+
if not all:
|
1358 |
+
if device == '' or fstype not in fstypes:
|
1359 |
+
continue
|
1360 |
+
maxfile = maxpath = None # set later
|
1361 |
+
ntuple = _common.sdiskpart(
|
1362 |
+
device, mountpoint, fstype, opts, maxfile, maxpath
|
1363 |
+
)
|
1364 |
+
retlist.append(ntuple)
|
1365 |
+
|
1366 |
+
return retlist
|
1367 |
+
|
1368 |
+
|
1369 |
+
# =====================================================================
|
1370 |
+
# --- sensors
|
1371 |
+
# =====================================================================
|
1372 |
+
|
1373 |
+
|
1374 |
+
def sensors_temperatures():
|
1375 |
+
"""Return hardware (CPU and others) temperatures as a dict
|
1376 |
+
including hardware name, label, current, max and critical
|
1377 |
+
temperatures.
|
1378 |
+
|
1379 |
+
Implementation notes:
|
1380 |
+
- /sys/class/hwmon looks like the most recent interface to
|
1381 |
+
retrieve this info, and this implementation relies on it
|
1382 |
+
only (old distros will probably use something else)
|
1383 |
+
- lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
|
1384 |
+
- /sys/class/thermal/thermal_zone* is another one but it's more
|
1385 |
+
difficult to parse
|
1386 |
+
"""
|
1387 |
+
ret = collections.defaultdict(list)
|
1388 |
+
basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*')
|
1389 |
+
# CentOS has an intermediate /device directory:
|
1390 |
+
# https://github.com/giampaolo/psutil/issues/971
|
1391 |
+
# https://github.com/nicolargo/glances/issues/1060
|
1392 |
+
basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*'))
|
1393 |
+
basenames = sorted(set([x.split('_')[0] for x in basenames]))
|
1394 |
+
|
1395 |
+
# Only add the coretemp hwmon entries if they're not already in
|
1396 |
+
# /sys/class/hwmon/
|
1397 |
+
# https://github.com/giampaolo/psutil/issues/1708
|
1398 |
+
# https://github.com/giampaolo/psutil/pull/1648
|
1399 |
+
basenames2 = glob.glob(
|
1400 |
+
'/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*'
|
1401 |
+
)
|
1402 |
+
repl = re.compile('/sys/devices/platform/coretemp.*/hwmon/')
|
1403 |
+
for name in basenames2:
|
1404 |
+
altname = repl.sub('/sys/class/hwmon/', name)
|
1405 |
+
if altname not in basenames:
|
1406 |
+
basenames.append(name)
|
1407 |
+
|
1408 |
+
for base in basenames:
|
1409 |
+
try:
|
1410 |
+
path = base + '_input'
|
1411 |
+
current = float(bcat(path)) / 1000.0
|
1412 |
+
path = os.path.join(os.path.dirname(base), 'name')
|
1413 |
+
unit_name = cat(path).strip()
|
1414 |
+
except (IOError, OSError, ValueError):
|
1415 |
+
# A lot of things can go wrong here, so let's just skip the
|
1416 |
+
# whole entry. Sure thing is Linux's /sys/class/hwmon really
|
1417 |
+
# is a stinky broken mess.
|
1418 |
+
# https://github.com/giampaolo/psutil/issues/1009
|
1419 |
+
# https://github.com/giampaolo/psutil/issues/1101
|
1420 |
+
# https://github.com/giampaolo/psutil/issues/1129
|
1421 |
+
# https://github.com/giampaolo/psutil/issues/1245
|
1422 |
+
# https://github.com/giampaolo/psutil/issues/1323
|
1423 |
+
continue
|
1424 |
+
|
1425 |
+
high = bcat(base + '_max', fallback=None)
|
1426 |
+
critical = bcat(base + '_crit', fallback=None)
|
1427 |
+
label = cat(base + '_label', fallback='').strip()
|
1428 |
+
|
1429 |
+
if high is not None:
|
1430 |
+
try:
|
1431 |
+
high = float(high) / 1000.0
|
1432 |
+
except ValueError:
|
1433 |
+
high = None
|
1434 |
+
if critical is not None:
|
1435 |
+
try:
|
1436 |
+
critical = float(critical) / 1000.0
|
1437 |
+
except ValueError:
|
1438 |
+
critical = None
|
1439 |
+
|
1440 |
+
ret[unit_name].append((label, current, high, critical))
|
1441 |
+
|
1442 |
+
# Indication that no sensors were detected in /sys/class/hwmon/
|
1443 |
+
if not basenames:
|
1444 |
+
basenames = glob.glob('/sys/class/thermal/thermal_zone*')
|
1445 |
+
basenames = sorted(set(basenames))
|
1446 |
+
|
1447 |
+
for base in basenames:
|
1448 |
+
try:
|
1449 |
+
path = os.path.join(base, 'temp')
|
1450 |
+
current = float(bcat(path)) / 1000.0
|
1451 |
+
path = os.path.join(base, 'type')
|
1452 |
+
unit_name = cat(path).strip()
|
1453 |
+
except (IOError, OSError, ValueError) as err:
|
1454 |
+
debug(err)
|
1455 |
+
continue
|
1456 |
+
|
1457 |
+
trip_paths = glob.glob(base + '/trip_point*')
|
1458 |
+
trip_points = set([
|
1459 |
+
'_'.join(os.path.basename(p).split('_')[0:3])
|
1460 |
+
for p in trip_paths
|
1461 |
+
])
|
1462 |
+
critical = None
|
1463 |
+
high = None
|
1464 |
+
for trip_point in trip_points:
|
1465 |
+
path = os.path.join(base, trip_point + "_type")
|
1466 |
+
trip_type = cat(path, fallback='').strip()
|
1467 |
+
if trip_type == 'critical':
|
1468 |
+
critical = bcat(
|
1469 |
+
os.path.join(base, trip_point + "_temp"), fallback=None
|
1470 |
+
)
|
1471 |
+
elif trip_type == 'high':
|
1472 |
+
high = bcat(
|
1473 |
+
os.path.join(base, trip_point + "_temp"), fallback=None
|
1474 |
+
)
|
1475 |
+
|
1476 |
+
if high is not None:
|
1477 |
+
try:
|
1478 |
+
high = float(high) / 1000.0
|
1479 |
+
except ValueError:
|
1480 |
+
high = None
|
1481 |
+
if critical is not None:
|
1482 |
+
try:
|
1483 |
+
critical = float(critical) / 1000.0
|
1484 |
+
except ValueError:
|
1485 |
+
critical = None
|
1486 |
+
|
1487 |
+
ret[unit_name].append(('', current, high, critical))
|
1488 |
+
|
1489 |
+
return dict(ret)
|
1490 |
+
|
1491 |
+
|
1492 |
+
def sensors_fans():
|
1493 |
+
"""Return hardware fans info (for CPU and other peripherals) as a
|
1494 |
+
dict including hardware label and current speed.
|
1495 |
+
|
1496 |
+
Implementation notes:
|
1497 |
+
- /sys/class/hwmon looks like the most recent interface to
|
1498 |
+
retrieve this info, and this implementation relies on it
|
1499 |
+
only (old distros will probably use something else)
|
1500 |
+
- lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
|
1501 |
+
"""
|
1502 |
+
ret = collections.defaultdict(list)
|
1503 |
+
basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
|
1504 |
+
if not basenames:
|
1505 |
+
# CentOS has an intermediate /device directory:
|
1506 |
+
# https://github.com/giampaolo/psutil/issues/971
|
1507 |
+
basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*')
|
1508 |
+
|
1509 |
+
basenames = sorted(set([x.split('_')[0] for x in basenames]))
|
1510 |
+
for base in basenames:
|
1511 |
+
try:
|
1512 |
+
current = int(bcat(base + '_input'))
|
1513 |
+
except (IOError, OSError) as err:
|
1514 |
+
debug(err)
|
1515 |
+
continue
|
1516 |
+
unit_name = cat(os.path.join(os.path.dirname(base), 'name')).strip()
|
1517 |
+
label = cat(base + '_label', fallback='').strip()
|
1518 |
+
ret[unit_name].append(_common.sfan(label, current))
|
1519 |
+
|
1520 |
+
return dict(ret)
|
1521 |
+
|
1522 |
+
|
1523 |
+
def sensors_battery():
|
1524 |
+
"""Return battery information.
|
1525 |
+
Implementation note: it appears /sys/class/power_supply/BAT0/
|
1526 |
+
directory structure may vary and provide files with the same
|
1527 |
+
meaning but under different names, see:
|
1528 |
+
https://github.com/giampaolo/psutil/issues/966.
|
1529 |
+
"""
|
1530 |
+
null = object()
|
1531 |
+
|
1532 |
+
def multi_bcat(*paths):
|
1533 |
+
"""Attempt to read the content of multiple files which may
|
1534 |
+
not exist. If none of them exist return None.
|
1535 |
+
"""
|
1536 |
+
for path in paths:
|
1537 |
+
ret = bcat(path, fallback=null)
|
1538 |
+
if ret != null:
|
1539 |
+
try:
|
1540 |
+
return int(ret)
|
1541 |
+
except ValueError:
|
1542 |
+
return ret.strip()
|
1543 |
+
return None
|
1544 |
+
|
1545 |
+
bats = [
|
1546 |
+
x
|
1547 |
+
for x in os.listdir(POWER_SUPPLY_PATH)
|
1548 |
+
if x.startswith('BAT') or 'battery' in x.lower()
|
1549 |
+
]
|
1550 |
+
if not bats:
|
1551 |
+
return None
|
1552 |
+
# Get the first available battery. Usually this is "BAT0", except
|
1553 |
+
# some rare exceptions:
|
1554 |
+
# https://github.com/giampaolo/psutil/issues/1238
|
1555 |
+
root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0])
|
1556 |
+
|
1557 |
+
# Base metrics.
|
1558 |
+
energy_now = multi_bcat(root + "/energy_now", root + "/charge_now")
|
1559 |
+
power_now = multi_bcat(root + "/power_now", root + "/current_now")
|
1560 |
+
energy_full = multi_bcat(root + "/energy_full", root + "/charge_full")
|
1561 |
+
time_to_empty = multi_bcat(root + "/time_to_empty_now")
|
1562 |
+
|
1563 |
+
# Percent. If we have energy_full the percentage will be more
|
1564 |
+
# accurate compared to reading /capacity file (float vs. int).
|
1565 |
+
if energy_full is not None and energy_now is not None:
|
1566 |
+
try:
|
1567 |
+
percent = 100.0 * energy_now / energy_full
|
1568 |
+
except ZeroDivisionError:
|
1569 |
+
percent = 0.0
|
1570 |
+
else:
|
1571 |
+
percent = int(cat(root + "/capacity", fallback=-1))
|
1572 |
+
if percent == -1:
|
1573 |
+
return None
|
1574 |
+
|
1575 |
+
# Is AC power cable plugged in?
|
1576 |
+
# Note: AC0 is not always available and sometimes (e.g. CentOS7)
|
1577 |
+
# it's called "AC".
|
1578 |
+
power_plugged = None
|
1579 |
+
online = multi_bcat(
|
1580 |
+
os.path.join(POWER_SUPPLY_PATH, "AC0/online"),
|
1581 |
+
os.path.join(POWER_SUPPLY_PATH, "AC/online"),
|
1582 |
+
)
|
1583 |
+
if online is not None:
|
1584 |
+
power_plugged = online == 1
|
1585 |
+
else:
|
1586 |
+
status = cat(root + "/status", fallback="").strip().lower()
|
1587 |
+
if status == "discharging":
|
1588 |
+
power_plugged = False
|
1589 |
+
elif status in ("charging", "full"):
|
1590 |
+
power_plugged = True
|
1591 |
+
|
1592 |
+
# Seconds left.
|
1593 |
+
# Note to self: we may also calculate the charging ETA as per:
|
1594 |
+
# https://github.com/thialfihar/dotfiles/blob/
|
1595 |
+
# 013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55
|
1596 |
+
if power_plugged:
|
1597 |
+
secsleft = _common.POWER_TIME_UNLIMITED
|
1598 |
+
elif energy_now is not None and power_now is not None:
|
1599 |
+
try:
|
1600 |
+
secsleft = int(energy_now / power_now * 3600)
|
1601 |
+
except ZeroDivisionError:
|
1602 |
+
secsleft = _common.POWER_TIME_UNKNOWN
|
1603 |
+
elif time_to_empty is not None:
|
1604 |
+
secsleft = int(time_to_empty * 60)
|
1605 |
+
if secsleft < 0:
|
1606 |
+
secsleft = _common.POWER_TIME_UNKNOWN
|
1607 |
+
else:
|
1608 |
+
secsleft = _common.POWER_TIME_UNKNOWN
|
1609 |
+
|
1610 |
+
return _common.sbattery(percent, secsleft, power_plugged)
|
1611 |
+
|
1612 |
+
|
1613 |
+
# =====================================================================
|
1614 |
+
# --- other system functions
|
1615 |
+
# =====================================================================
|
1616 |
+
|
1617 |
+
|
1618 |
+
def users():
|
1619 |
+
"""Return currently connected users as a list of namedtuples."""
|
1620 |
+
retlist = []
|
1621 |
+
rawlist = cext.users()
|
1622 |
+
for item in rawlist:
|
1623 |
+
user, tty, hostname, tstamp, pid = item
|
1624 |
+
nt = _common.suser(user, tty or None, hostname, tstamp, pid)
|
1625 |
+
retlist.append(nt)
|
1626 |
+
return retlist
|
1627 |
+
|
1628 |
+
|
1629 |
+
def boot_time():
|
1630 |
+
"""Return the system boot time expressed in seconds since the epoch."""
|
1631 |
+
global BOOT_TIME
|
1632 |
+
path = '%s/stat' % get_procfs_path()
|
1633 |
+
with open_binary(path) as f:
|
1634 |
+
for line in f:
|
1635 |
+
if line.startswith(b'btime'):
|
1636 |
+
ret = float(line.strip().split()[1])
|
1637 |
+
BOOT_TIME = ret
|
1638 |
+
return ret
|
1639 |
+
raise RuntimeError("line 'btime' not found in %s" % path)
|
1640 |
+
|
1641 |
+
|
1642 |
+
# =====================================================================
|
1643 |
+
# --- processes
|
1644 |
+
# =====================================================================
|
1645 |
+
|
1646 |
+
|
1647 |
+
def pids():
|
1648 |
+
"""Returns a list of PIDs currently running on the system."""
|
1649 |
+
return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
|
1650 |
+
|
1651 |
+
|
1652 |
+
def pid_exists(pid):
|
1653 |
+
"""Check for the existence of a unix PID. Linux TIDs are not
|
1654 |
+
supported (always return False).
|
1655 |
+
"""
|
1656 |
+
if not _psposix.pid_exists(pid):
|
1657 |
+
return False
|
1658 |
+
else:
|
1659 |
+
# Linux's apparently does not distinguish between PIDs and TIDs
|
1660 |
+
# (thread IDs).
|
1661 |
+
# listdir("/proc") won't show any TID (only PIDs) but
|
1662 |
+
# os.stat("/proc/{tid}") will succeed if {tid} exists.
|
1663 |
+
# os.kill() can also be passed a TID. This is quite confusing.
|
1664 |
+
# In here we want to enforce this distinction and support PIDs
|
1665 |
+
# only, see:
|
1666 |
+
# https://github.com/giampaolo/psutil/issues/687
|
1667 |
+
try:
|
1668 |
+
# Note: already checked that this is faster than using a
|
1669 |
+
# regular expr. Also (a lot) faster than doing
|
1670 |
+
# 'return pid in pids()'
|
1671 |
+
path = "%s/%s/status" % (get_procfs_path(), pid)
|
1672 |
+
with open_binary(path) as f:
|
1673 |
+
for line in f:
|
1674 |
+
if line.startswith(b"Tgid:"):
|
1675 |
+
tgid = int(line.split()[1])
|
1676 |
+
# If tgid and pid are the same then we're
|
1677 |
+
# dealing with a process PID.
|
1678 |
+
return tgid == pid
|
1679 |
+
raise ValueError("'Tgid' line not found in %s" % path)
|
1680 |
+
except (EnvironmentError, ValueError):
|
1681 |
+
return pid in pids()
|
1682 |
+
|
1683 |
+
|
1684 |
+
def ppid_map():
|
1685 |
+
"""Obtain a {pid: ppid, ...} dict for all running processes in
|
1686 |
+
one shot. Used to speed up Process.children().
|
1687 |
+
"""
|
1688 |
+
ret = {}
|
1689 |
+
procfs_path = get_procfs_path()
|
1690 |
+
for pid in pids():
|
1691 |
+
try:
|
1692 |
+
with open_binary("%s/%s/stat" % (procfs_path, pid)) as f:
|
1693 |
+
data = f.read()
|
1694 |
+
except (FileNotFoundError, ProcessLookupError):
|
1695 |
+
# Note: we should be able to access /stat for all processes
|
1696 |
+
# aka it's unlikely we'll bump into EPERM, which is good.
|
1697 |
+
pass
|
1698 |
+
else:
|
1699 |
+
rpar = data.rfind(b')')
|
1700 |
+
dset = data[rpar + 2 :].split()
|
1701 |
+
ppid = int(dset[1])
|
1702 |
+
ret[pid] = ppid
|
1703 |
+
return ret
|
1704 |
+
|
1705 |
+
|
1706 |
+
def wrap_exceptions(fun):
|
1707 |
+
"""Decorator which translates bare OSError and IOError exceptions
|
1708 |
+
into NoSuchProcess and AccessDenied.
|
1709 |
+
"""
|
1710 |
+
|
1711 |
+
@functools.wraps(fun)
|
1712 |
+
def wrapper(self, *args, **kwargs):
|
1713 |
+
try:
|
1714 |
+
return fun(self, *args, **kwargs)
|
1715 |
+
except PermissionError:
|
1716 |
+
raise AccessDenied(self.pid, self._name)
|
1717 |
+
except ProcessLookupError:
|
1718 |
+
self._raise_if_zombie()
|
1719 |
+
raise NoSuchProcess(self.pid, self._name)
|
1720 |
+
except FileNotFoundError:
|
1721 |
+
self._raise_if_zombie()
|
1722 |
+
if not os.path.exists("%s/%s" % (self._procfs_path, self.pid)):
|
1723 |
+
raise NoSuchProcess(self.pid, self._name)
|
1724 |
+
raise
|
1725 |
+
|
1726 |
+
return wrapper
|
1727 |
+
|
1728 |
+
|
1729 |
+
class Process:
|
1730 |
+
"""Linux process implementation."""
|
1731 |
+
|
1732 |
+
__slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
|
1733 |
+
|
1734 |
+
def __init__(self, pid):
|
1735 |
+
self.pid = pid
|
1736 |
+
self._name = None
|
1737 |
+
self._ppid = None
|
1738 |
+
self._procfs_path = get_procfs_path()
|
1739 |
+
|
1740 |
+
def _is_zombie(self):
|
1741 |
+
# Note: most of the times Linux is able to return info about the
|
1742 |
+
# process even if it's a zombie, and /proc/{pid} will exist.
|
1743 |
+
# There are some exceptions though, like exe(), cmdline() and
|
1744 |
+
# memory_maps(). In these cases /proc/{pid}/{file} exists but
|
1745 |
+
# it's empty. Instead of returning a "null" value we'll raise an
|
1746 |
+
# exception.
|
1747 |
+
try:
|
1748 |
+
data = bcat("%s/%s/stat" % (self._procfs_path, self.pid))
|
1749 |
+
except (IOError, OSError):
|
1750 |
+
return False
|
1751 |
+
else:
|
1752 |
+
rpar = data.rfind(b')')
|
1753 |
+
status = data[rpar + 2 : rpar + 3]
|
1754 |
+
return status == b"Z"
|
1755 |
+
|
1756 |
+
def _raise_if_zombie(self):
|
1757 |
+
if self._is_zombie():
|
1758 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
1759 |
+
|
1760 |
+
def _raise_if_not_alive(self):
|
1761 |
+
"""Raise NSP if the process disappeared on us."""
|
1762 |
+
# For those C function who do not raise NSP, possibly returning
|
1763 |
+
# incorrect or incomplete result.
|
1764 |
+
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
1765 |
+
|
1766 |
+
@wrap_exceptions
|
1767 |
+
@memoize_when_activated
|
1768 |
+
def _parse_stat_file(self):
|
1769 |
+
"""Parse /proc/{pid}/stat file and return a dict with various
|
1770 |
+
process info.
|
1771 |
+
Using "man proc" as a reference: where "man proc" refers to
|
1772 |
+
position N always subtract 3 (e.g ppid position 4 in
|
1773 |
+
'man proc' == position 1 in here).
|
1774 |
+
The return value is cached in case oneshot() ctx manager is
|
1775 |
+
in use.
|
1776 |
+
"""
|
1777 |
+
data = bcat("%s/%s/stat" % (self._procfs_path, self.pid))
|
1778 |
+
# Process name is between parentheses. It can contain spaces and
|
1779 |
+
# other parentheses. This is taken into account by looking for
|
1780 |
+
# the first occurrence of "(" and the last occurrence of ")".
|
1781 |
+
rpar = data.rfind(b')')
|
1782 |
+
name = data[data.find(b'(') + 1 : rpar]
|
1783 |
+
fields = data[rpar + 2 :].split()
|
1784 |
+
|
1785 |
+
ret = {}
|
1786 |
+
ret['name'] = name
|
1787 |
+
ret['status'] = fields[0]
|
1788 |
+
ret['ppid'] = fields[1]
|
1789 |
+
ret['ttynr'] = fields[4]
|
1790 |
+
ret['utime'] = fields[11]
|
1791 |
+
ret['stime'] = fields[12]
|
1792 |
+
ret['children_utime'] = fields[13]
|
1793 |
+
ret['children_stime'] = fields[14]
|
1794 |
+
ret['create_time'] = fields[19]
|
1795 |
+
ret['cpu_num'] = fields[36]
|
1796 |
+
ret['blkio_ticks'] = fields[39] # aka 'delayacct_blkio_ticks'
|
1797 |
+
|
1798 |
+
return ret
|
1799 |
+
|
1800 |
+
@wrap_exceptions
|
1801 |
+
@memoize_when_activated
|
1802 |
+
def _read_status_file(self):
|
1803 |
+
"""Read /proc/{pid}/stat file and return its content.
|
1804 |
+
The return value is cached in case oneshot() ctx manager is
|
1805 |
+
in use.
|
1806 |
+
"""
|
1807 |
+
with open_binary("%s/%s/status" % (self._procfs_path, self.pid)) as f:
|
1808 |
+
return f.read()
|
1809 |
+
|
1810 |
+
@wrap_exceptions
|
1811 |
+
@memoize_when_activated
|
1812 |
+
def _read_smaps_file(self):
|
1813 |
+
with open_binary("%s/%s/smaps" % (self._procfs_path, self.pid)) as f:
|
1814 |
+
return f.read().strip()
|
1815 |
+
|
1816 |
+
def oneshot_enter(self):
|
1817 |
+
self._parse_stat_file.cache_activate(self)
|
1818 |
+
self._read_status_file.cache_activate(self)
|
1819 |
+
self._read_smaps_file.cache_activate(self)
|
1820 |
+
|
1821 |
+
def oneshot_exit(self):
|
1822 |
+
self._parse_stat_file.cache_deactivate(self)
|
1823 |
+
self._read_status_file.cache_deactivate(self)
|
1824 |
+
self._read_smaps_file.cache_deactivate(self)
|
1825 |
+
|
1826 |
+
@wrap_exceptions
|
1827 |
+
def name(self):
|
1828 |
+
name = self._parse_stat_file()['name']
|
1829 |
+
if PY3:
|
1830 |
+
name = decode(name)
|
1831 |
+
# XXX - gets changed later and probably needs refactoring
|
1832 |
+
return name
|
1833 |
+
|
1834 |
+
@wrap_exceptions
|
1835 |
+
def exe(self):
|
1836 |
+
try:
|
1837 |
+
return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
|
1838 |
+
except (FileNotFoundError, ProcessLookupError):
|
1839 |
+
self._raise_if_zombie()
|
1840 |
+
# no such file error; might be raised also if the
|
1841 |
+
# path actually exists for system processes with
|
1842 |
+
# low pids (about 0-20)
|
1843 |
+
if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
|
1844 |
+
return ""
|
1845 |
+
raise
|
1846 |
+
|
1847 |
+
@wrap_exceptions
|
1848 |
+
def cmdline(self):
|
1849 |
+
with open_text("%s/%s/cmdline" % (self._procfs_path, self.pid)) as f:
|
1850 |
+
data = f.read()
|
1851 |
+
if not data:
|
1852 |
+
# may happen in case of zombie process
|
1853 |
+
self._raise_if_zombie()
|
1854 |
+
return []
|
1855 |
+
# 'man proc' states that args are separated by null bytes '\0'
|
1856 |
+
# and last char is supposed to be a null byte. Nevertheless
|
1857 |
+
# some processes may change their cmdline after being started
|
1858 |
+
# (via setproctitle() or similar), they are usually not
|
1859 |
+
# compliant with this rule and use spaces instead. Google
|
1860 |
+
# Chrome process is an example. See:
|
1861 |
+
# https://github.com/giampaolo/psutil/issues/1179
|
1862 |
+
sep = '\x00' if data.endswith('\x00') else ' '
|
1863 |
+
if data.endswith(sep):
|
1864 |
+
data = data[:-1]
|
1865 |
+
cmdline = data.split(sep)
|
1866 |
+
# Sometimes last char is a null byte '\0' but the args are
|
1867 |
+
# separated by spaces, see: https://github.com/giampaolo/psutil/
|
1868 |
+
# issues/1179#issuecomment-552984549
|
1869 |
+
if sep == '\x00' and len(cmdline) == 1 and ' ' in data:
|
1870 |
+
cmdline = data.split(' ')
|
1871 |
+
return cmdline
|
1872 |
+
|
1873 |
+
@wrap_exceptions
|
1874 |
+
def environ(self):
|
1875 |
+
with open_text("%s/%s/environ" % (self._procfs_path, self.pid)) as f:
|
1876 |
+
data = f.read()
|
1877 |
+
return parse_environ_block(data)
|
1878 |
+
|
1879 |
+
@wrap_exceptions
|
1880 |
+
def terminal(self):
|
1881 |
+
tty_nr = int(self._parse_stat_file()['ttynr'])
|
1882 |
+
tmap = _psposix.get_terminal_map()
|
1883 |
+
try:
|
1884 |
+
return tmap[tty_nr]
|
1885 |
+
except KeyError:
|
1886 |
+
return None
|
1887 |
+
|
1888 |
+
# May not be available on old kernels.
|
1889 |
+
if os.path.exists('/proc/%s/io' % os.getpid()):
|
1890 |
+
|
1891 |
+
@wrap_exceptions
|
1892 |
+
def io_counters(self):
|
1893 |
+
fname = "%s/%s/io" % (self._procfs_path, self.pid)
|
1894 |
+
fields = {}
|
1895 |
+
with open_binary(fname) as f:
|
1896 |
+
for line in f:
|
1897 |
+
# https://github.com/giampaolo/psutil/issues/1004
|
1898 |
+
line = line.strip()
|
1899 |
+
if line:
|
1900 |
+
try:
|
1901 |
+
name, value = line.split(b': ')
|
1902 |
+
except ValueError:
|
1903 |
+
# https://github.com/giampaolo/psutil/issues/1004
|
1904 |
+
continue
|
1905 |
+
else:
|
1906 |
+
fields[name] = int(value)
|
1907 |
+
if not fields:
|
1908 |
+
raise RuntimeError("%s file was empty" % fname)
|
1909 |
+
try:
|
1910 |
+
return pio(
|
1911 |
+
fields[b'syscr'], # read syscalls
|
1912 |
+
fields[b'syscw'], # write syscalls
|
1913 |
+
fields[b'read_bytes'], # read bytes
|
1914 |
+
fields[b'write_bytes'], # write bytes
|
1915 |
+
fields[b'rchar'], # read chars
|
1916 |
+
fields[b'wchar'], # write chars
|
1917 |
+
)
|
1918 |
+
except KeyError as err:
|
1919 |
+
raise ValueError(
|
1920 |
+
"%r field was not found in %s; found fields are %r"
|
1921 |
+
% (err.args[0], fname, fields)
|
1922 |
+
)
|
1923 |
+
|
1924 |
+
@wrap_exceptions
|
1925 |
+
def cpu_times(self):
|
1926 |
+
values = self._parse_stat_file()
|
1927 |
+
utime = float(values['utime']) / CLOCK_TICKS
|
1928 |
+
stime = float(values['stime']) / CLOCK_TICKS
|
1929 |
+
children_utime = float(values['children_utime']) / CLOCK_TICKS
|
1930 |
+
children_stime = float(values['children_stime']) / CLOCK_TICKS
|
1931 |
+
iowait = float(values['blkio_ticks']) / CLOCK_TICKS
|
1932 |
+
return pcputimes(utime, stime, children_utime, children_stime, iowait)
|
1933 |
+
|
1934 |
+
@wrap_exceptions
|
1935 |
+
def cpu_num(self):
|
1936 |
+
"""What CPU the process is on."""
|
1937 |
+
return int(self._parse_stat_file()['cpu_num'])
|
1938 |
+
|
1939 |
+
@wrap_exceptions
|
1940 |
+
def wait(self, timeout=None):
|
1941 |
+
return _psposix.wait_pid(self.pid, timeout, self._name)
|
1942 |
+
|
1943 |
+
@wrap_exceptions
|
1944 |
+
def create_time(self):
|
1945 |
+
ctime = float(self._parse_stat_file()['create_time'])
|
1946 |
+
# According to documentation, starttime is in field 21 and the
|
1947 |
+
# unit is jiffies (clock ticks).
|
1948 |
+
# We first divide it for clock ticks and then add uptime returning
|
1949 |
+
# seconds since the epoch.
|
1950 |
+
# Also use cached value if available.
|
1951 |
+
bt = BOOT_TIME or boot_time()
|
1952 |
+
return (ctime / CLOCK_TICKS) + bt
|
1953 |
+
|
1954 |
+
@wrap_exceptions
|
1955 |
+
def memory_info(self):
|
1956 |
+
# ============================================================
|
1957 |
+
# | FIELD | DESCRIPTION | AKA | TOP |
|
1958 |
+
# ============================================================
|
1959 |
+
# | rss | resident set size | | RES |
|
1960 |
+
# | vms | total program size | size | VIRT |
|
1961 |
+
# | shared | shared pages (from shared mappings) | | SHR |
|
1962 |
+
# | text | text ('code') | trs | CODE |
|
1963 |
+
# | lib | library (unused in Linux 2.6) | lrs | |
|
1964 |
+
# | data | data + stack | drs | DATA |
|
1965 |
+
# | dirty | dirty pages (unused in Linux 2.6) | dt | |
|
1966 |
+
# ============================================================
|
1967 |
+
with open_binary("%s/%s/statm" % (self._procfs_path, self.pid)) as f:
|
1968 |
+
vms, rss, shared, text, lib, data, dirty = (
|
1969 |
+
int(x) * PAGESIZE for x in f.readline().split()[:7]
|
1970 |
+
)
|
1971 |
+
return pmem(rss, vms, shared, text, lib, data, dirty)
|
1972 |
+
|
1973 |
+
if HAS_PROC_SMAPS_ROLLUP or HAS_PROC_SMAPS:
|
1974 |
+
|
1975 |
+
def _parse_smaps_rollup(self):
|
1976 |
+
# /proc/pid/smaps_rollup was added to Linux in 2017. Faster
|
1977 |
+
# than /proc/pid/smaps. It reports higher PSS than */smaps
|
1978 |
+
# (from 1k up to 200k higher; tested against all processes).
|
1979 |
+
# IMPORTANT: /proc/pid/smaps_rollup is weird, because it
|
1980 |
+
# raises ESRCH / ENOENT for many PIDs, even if they're alive
|
1981 |
+
# (also as root). In that case we'll use /proc/pid/smaps as
|
1982 |
+
# fallback, which is slower but has a +50% success rate
|
1983 |
+
# compared to /proc/pid/smaps_rollup.
|
1984 |
+
uss = pss = swap = 0
|
1985 |
+
with open_binary(
|
1986 |
+
"{}/{}/smaps_rollup".format(self._procfs_path, self.pid)
|
1987 |
+
) as f:
|
1988 |
+
for line in f:
|
1989 |
+
if line.startswith(b"Private_"):
|
1990 |
+
# Private_Clean, Private_Dirty, Private_Hugetlb
|
1991 |
+
uss += int(line.split()[1]) * 1024
|
1992 |
+
elif line.startswith(b"Pss:"):
|
1993 |
+
pss = int(line.split()[1]) * 1024
|
1994 |
+
elif line.startswith(b"Swap:"):
|
1995 |
+
swap = int(line.split()[1]) * 1024
|
1996 |
+
return (uss, pss, swap)
|
1997 |
+
|
1998 |
+
@wrap_exceptions
|
1999 |
+
def _parse_smaps(
|
2000 |
+
self,
|
2001 |
+
# Gets Private_Clean, Private_Dirty, Private_Hugetlb.
|
2002 |
+
_private_re=re.compile(br"\nPrivate.*:\s+(\d+)"),
|
2003 |
+
_pss_re=re.compile(br"\nPss\:\s+(\d+)"),
|
2004 |
+
_swap_re=re.compile(br"\nSwap\:\s+(\d+)"),
|
2005 |
+
):
|
2006 |
+
# /proc/pid/smaps does not exist on kernels < 2.6.14 or if
|
2007 |
+
# CONFIG_MMU kernel configuration option is not enabled.
|
2008 |
+
|
2009 |
+
# Note: using 3 regexes is faster than reading the file
|
2010 |
+
# line by line.
|
2011 |
+
# XXX: on Python 3 the 2 regexes are 30% slower than on
|
2012 |
+
# Python 2 though. Figure out why.
|
2013 |
+
#
|
2014 |
+
# You might be tempted to calculate USS by subtracting
|
2015 |
+
# the "shared" value from the "resident" value in
|
2016 |
+
# /proc/<pid>/statm. But at least on Linux, statm's "shared"
|
2017 |
+
# value actually counts pages backed by files, which has
|
2018 |
+
# little to do with whether the pages are actually shared.
|
2019 |
+
# /proc/self/smaps on the other hand appears to give us the
|
2020 |
+
# correct information.
|
2021 |
+
smaps_data = self._read_smaps_file()
|
2022 |
+
# Note: smaps file can be empty for certain processes.
|
2023 |
+
# The code below will not crash though and will result to 0.
|
2024 |
+
uss = sum(map(int, _private_re.findall(smaps_data))) * 1024
|
2025 |
+
pss = sum(map(int, _pss_re.findall(smaps_data))) * 1024
|
2026 |
+
swap = sum(map(int, _swap_re.findall(smaps_data))) * 1024
|
2027 |
+
return (uss, pss, swap)
|
2028 |
+
|
2029 |
+
@wrap_exceptions
|
2030 |
+
def memory_full_info(self):
|
2031 |
+
if HAS_PROC_SMAPS_ROLLUP: # faster
|
2032 |
+
try:
|
2033 |
+
uss, pss, swap = self._parse_smaps_rollup()
|
2034 |
+
except (ProcessLookupError, FileNotFoundError):
|
2035 |
+
uss, pss, swap = self._parse_smaps()
|
2036 |
+
else:
|
2037 |
+
uss, pss, swap = self._parse_smaps()
|
2038 |
+
basic_mem = self.memory_info()
|
2039 |
+
return pfullmem(*basic_mem + (uss, pss, swap))
|
2040 |
+
|
2041 |
+
else:
|
2042 |
+
memory_full_info = memory_info
|
2043 |
+
|
2044 |
+
if HAS_PROC_SMAPS:
|
2045 |
+
|
2046 |
+
@wrap_exceptions
|
2047 |
+
def memory_maps(self):
|
2048 |
+
"""Return process's mapped memory regions as a list of named
|
2049 |
+
tuples. Fields are explained in 'man proc'; here is an updated
|
2050 |
+
(Apr 2012) version: http://goo.gl/fmebo.
|
2051 |
+
|
2052 |
+
/proc/{PID}/smaps does not exist on kernels < 2.6.14 or if
|
2053 |
+
CONFIG_MMU kernel configuration option is not enabled.
|
2054 |
+
"""
|
2055 |
+
|
2056 |
+
def get_blocks(lines, current_block):
|
2057 |
+
data = {}
|
2058 |
+
for line in lines:
|
2059 |
+
fields = line.split(None, 5)
|
2060 |
+
if not fields[0].endswith(b':'):
|
2061 |
+
# new block section
|
2062 |
+
yield (current_block.pop(), data)
|
2063 |
+
current_block.append(line)
|
2064 |
+
else:
|
2065 |
+
try:
|
2066 |
+
data[fields[0]] = int(fields[1]) * 1024
|
2067 |
+
except ValueError:
|
2068 |
+
if fields[0].startswith(b'VmFlags:'):
|
2069 |
+
# see issue #369
|
2070 |
+
continue
|
2071 |
+
else:
|
2072 |
+
raise ValueError(
|
2073 |
+
"don't know how to interpret line %r"
|
2074 |
+
% line
|
2075 |
+
)
|
2076 |
+
yield (current_block.pop(), data)
|
2077 |
+
|
2078 |
+
data = self._read_smaps_file()
|
2079 |
+
# Note: smaps file can be empty for certain processes or for
|
2080 |
+
# zombies.
|
2081 |
+
if not data:
|
2082 |
+
self._raise_if_zombie()
|
2083 |
+
return []
|
2084 |
+
lines = data.split(b'\n')
|
2085 |
+
ls = []
|
2086 |
+
first_line = lines.pop(0)
|
2087 |
+
current_block = [first_line]
|
2088 |
+
for header, data in get_blocks(lines, current_block):
|
2089 |
+
hfields = header.split(None, 5)
|
2090 |
+
try:
|
2091 |
+
addr, perms, offset, dev, inode, path = hfields
|
2092 |
+
except ValueError:
|
2093 |
+
addr, perms, offset, dev, inode, path = hfields + ['']
|
2094 |
+
if not path:
|
2095 |
+
path = '[anon]'
|
2096 |
+
else:
|
2097 |
+
if PY3:
|
2098 |
+
path = decode(path)
|
2099 |
+
path = path.strip()
|
2100 |
+
if path.endswith(' (deleted)') and not path_exists_strict(
|
2101 |
+
path
|
2102 |
+
):
|
2103 |
+
path = path[:-10]
|
2104 |
+
ls.append((
|
2105 |
+
decode(addr),
|
2106 |
+
decode(perms),
|
2107 |
+
path,
|
2108 |
+
data.get(b'Rss:', 0),
|
2109 |
+
data.get(b'Size:', 0),
|
2110 |
+
data.get(b'Pss:', 0),
|
2111 |
+
data.get(b'Shared_Clean:', 0),
|
2112 |
+
data.get(b'Shared_Dirty:', 0),
|
2113 |
+
data.get(b'Private_Clean:', 0),
|
2114 |
+
data.get(b'Private_Dirty:', 0),
|
2115 |
+
data.get(b'Referenced:', 0),
|
2116 |
+
data.get(b'Anonymous:', 0),
|
2117 |
+
data.get(b'Swap:', 0),
|
2118 |
+
))
|
2119 |
+
return ls
|
2120 |
+
|
2121 |
+
@wrap_exceptions
|
2122 |
+
def cwd(self):
|
2123 |
+
return readlink("%s/%s/cwd" % (self._procfs_path, self.pid))
|
2124 |
+
|
2125 |
+
@wrap_exceptions
|
2126 |
+
def num_ctx_switches(
|
2127 |
+
self, _ctxsw_re=re.compile(br'ctxt_switches:\t(\d+)')
|
2128 |
+
):
|
2129 |
+
data = self._read_status_file()
|
2130 |
+
ctxsw = _ctxsw_re.findall(data)
|
2131 |
+
if not ctxsw:
|
2132 |
+
raise NotImplementedError(
|
2133 |
+
"'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'"
|
2134 |
+
"lines were not found in %s/%s/status; the kernel is "
|
2135 |
+
"probably older than 2.6.23" % (self._procfs_path, self.pid)
|
2136 |
+
)
|
2137 |
+
else:
|
2138 |
+
return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1]))
|
2139 |
+
|
2140 |
+
@wrap_exceptions
|
2141 |
+
def num_threads(self, _num_threads_re=re.compile(br'Threads:\t(\d+)')):
|
2142 |
+
# Note: on Python 3 using a re is faster than iterating over file
|
2143 |
+
# line by line. On Python 2 is the exact opposite, and iterating
|
2144 |
+
# over a file on Python 3 is slower than on Python 2.
|
2145 |
+
data = self._read_status_file()
|
2146 |
+
return int(_num_threads_re.findall(data)[0])
|
2147 |
+
|
2148 |
+
@wrap_exceptions
|
2149 |
+
def threads(self):
|
2150 |
+
thread_ids = os.listdir("%s/%s/task" % (self._procfs_path, self.pid))
|
2151 |
+
thread_ids.sort()
|
2152 |
+
retlist = []
|
2153 |
+
hit_enoent = False
|
2154 |
+
for thread_id in thread_ids:
|
2155 |
+
fname = "%s/%s/task/%s/stat" % (
|
2156 |
+
self._procfs_path,
|
2157 |
+
self.pid,
|
2158 |
+
thread_id,
|
2159 |
+
)
|
2160 |
+
try:
|
2161 |
+
with open_binary(fname) as f:
|
2162 |
+
st = f.read().strip()
|
2163 |
+
except (FileNotFoundError, ProcessLookupError):
|
2164 |
+
# no such file or directory or no such process;
|
2165 |
+
# it means thread disappeared on us
|
2166 |
+
hit_enoent = True
|
2167 |
+
continue
|
2168 |
+
# ignore the first two values ("pid (exe)")
|
2169 |
+
st = st[st.find(b')') + 2 :]
|
2170 |
+
values = st.split(b' ')
|
2171 |
+
utime = float(values[11]) / CLOCK_TICKS
|
2172 |
+
stime = float(values[12]) / CLOCK_TICKS
|
2173 |
+
ntuple = _common.pthread(int(thread_id), utime, stime)
|
2174 |
+
retlist.append(ntuple)
|
2175 |
+
if hit_enoent:
|
2176 |
+
self._raise_if_not_alive()
|
2177 |
+
return retlist
|
2178 |
+
|
2179 |
+
@wrap_exceptions
|
2180 |
+
def nice_get(self):
|
2181 |
+
# with open_text('%s/%s/stat' % (self._procfs_path, self.pid)) as f:
|
2182 |
+
# data = f.read()
|
2183 |
+
# return int(data.split()[18])
|
2184 |
+
|
2185 |
+
# Use C implementation
|
2186 |
+
return cext_posix.getpriority(self.pid)
|
2187 |
+
|
2188 |
+
@wrap_exceptions
|
2189 |
+
def nice_set(self, value):
|
2190 |
+
return cext_posix.setpriority(self.pid, value)
|
2191 |
+
|
2192 |
+
# starting from CentOS 6.
|
2193 |
+
if HAS_CPU_AFFINITY:
|
2194 |
+
|
2195 |
+
@wrap_exceptions
|
2196 |
+
def cpu_affinity_get(self):
|
2197 |
+
return cext.proc_cpu_affinity_get(self.pid)
|
2198 |
+
|
2199 |
+
def _get_eligible_cpus(
|
2200 |
+
self, _re=re.compile(br"Cpus_allowed_list:\t(\d+)-(\d+)")
|
2201 |
+
):
|
2202 |
+
# See: https://github.com/giampaolo/psutil/issues/956
|
2203 |
+
data = self._read_status_file()
|
2204 |
+
match = _re.findall(data)
|
2205 |
+
if match:
|
2206 |
+
return list(range(int(match[0][0]), int(match[0][1]) + 1))
|
2207 |
+
else:
|
2208 |
+
return list(range(len(per_cpu_times())))
|
2209 |
+
|
2210 |
+
@wrap_exceptions
|
2211 |
+
def cpu_affinity_set(self, cpus):
|
2212 |
+
try:
|
2213 |
+
cext.proc_cpu_affinity_set(self.pid, cpus)
|
2214 |
+
except (OSError, ValueError) as err:
|
2215 |
+
if isinstance(err, ValueError) or err.errno == errno.EINVAL:
|
2216 |
+
eligible_cpus = self._get_eligible_cpus()
|
2217 |
+
all_cpus = tuple(range(len(per_cpu_times())))
|
2218 |
+
for cpu in cpus:
|
2219 |
+
if cpu not in all_cpus:
|
2220 |
+
raise ValueError(
|
2221 |
+
"invalid CPU number %r; choose between %s"
|
2222 |
+
% (cpu, eligible_cpus)
|
2223 |
+
)
|
2224 |
+
if cpu not in eligible_cpus:
|
2225 |
+
raise ValueError(
|
2226 |
+
"CPU number %r is not eligible; choose "
|
2227 |
+
"between %s" % (cpu, eligible_cpus)
|
2228 |
+
)
|
2229 |
+
raise
|
2230 |
+
|
2231 |
+
# only starting from kernel 2.6.13
|
2232 |
+
if HAS_PROC_IO_PRIORITY:
|
2233 |
+
|
2234 |
+
@wrap_exceptions
|
2235 |
+
def ionice_get(self):
|
2236 |
+
ioclass, value = cext.proc_ioprio_get(self.pid)
|
2237 |
+
if enum is not None:
|
2238 |
+
ioclass = IOPriority(ioclass)
|
2239 |
+
return _common.pionice(ioclass, value)
|
2240 |
+
|
2241 |
+
@wrap_exceptions
|
2242 |
+
def ionice_set(self, ioclass, value):
|
2243 |
+
if value is None:
|
2244 |
+
value = 0
|
2245 |
+
if value and ioclass in (IOPRIO_CLASS_IDLE, IOPRIO_CLASS_NONE):
|
2246 |
+
raise ValueError("%r ioclass accepts no value" % ioclass)
|
2247 |
+
if value < 0 or value > 7:
|
2248 |
+
msg = "value not in 0-7 range"
|
2249 |
+
raise ValueError(msg)
|
2250 |
+
return cext.proc_ioprio_set(self.pid, ioclass, value)
|
2251 |
+
|
2252 |
+
if prlimit is not None:
|
2253 |
+
|
2254 |
+
@wrap_exceptions
|
2255 |
+
def rlimit(self, resource_, limits=None):
|
2256 |
+
# If pid is 0 prlimit() applies to the calling process and
|
2257 |
+
# we don't want that. We should never get here though as
|
2258 |
+
# PID 0 is not supported on Linux.
|
2259 |
+
if self.pid == 0:
|
2260 |
+
msg = "can't use prlimit() against PID 0 process"
|
2261 |
+
raise ValueError(msg)
|
2262 |
+
try:
|
2263 |
+
if limits is None:
|
2264 |
+
# get
|
2265 |
+
return prlimit(self.pid, resource_)
|
2266 |
+
else:
|
2267 |
+
# set
|
2268 |
+
if len(limits) != 2:
|
2269 |
+
msg = (
|
2270 |
+
"second argument must be a (soft, hard) "
|
2271 |
+
+ "tuple, got %s" % repr(limits)
|
2272 |
+
)
|
2273 |
+
raise ValueError(msg)
|
2274 |
+
prlimit(self.pid, resource_, limits)
|
2275 |
+
except OSError as err:
|
2276 |
+
if err.errno == errno.ENOSYS:
|
2277 |
+
# I saw this happening on Travis:
|
2278 |
+
# https://travis-ci.org/giampaolo/psutil/jobs/51368273
|
2279 |
+
self._raise_if_zombie()
|
2280 |
+
raise
|
2281 |
+
|
2282 |
+
@wrap_exceptions
|
2283 |
+
def status(self):
|
2284 |
+
letter = self._parse_stat_file()['status']
|
2285 |
+
if PY3:
|
2286 |
+
letter = letter.decode()
|
2287 |
+
# XXX is '?' legit? (we're not supposed to return it anyway)
|
2288 |
+
return PROC_STATUSES.get(letter, '?')
|
2289 |
+
|
2290 |
+
@wrap_exceptions
|
2291 |
+
def open_files(self):
|
2292 |
+
retlist = []
|
2293 |
+
files = os.listdir("%s/%s/fd" % (self._procfs_path, self.pid))
|
2294 |
+
hit_enoent = False
|
2295 |
+
for fd in files:
|
2296 |
+
file = "%s/%s/fd/%s" % (self._procfs_path, self.pid, fd)
|
2297 |
+
try:
|
2298 |
+
path = readlink(file)
|
2299 |
+
except (FileNotFoundError, ProcessLookupError):
|
2300 |
+
# ENOENT == file which is gone in the meantime
|
2301 |
+
hit_enoent = True
|
2302 |
+
continue
|
2303 |
+
except OSError as err:
|
2304 |
+
if err.errno == errno.EINVAL:
|
2305 |
+
# not a link
|
2306 |
+
continue
|
2307 |
+
if err.errno == errno.ENAMETOOLONG:
|
2308 |
+
# file name too long
|
2309 |
+
debug(err)
|
2310 |
+
continue
|
2311 |
+
raise
|
2312 |
+
else:
|
2313 |
+
# If path is not an absolute there's no way to tell
|
2314 |
+
# whether it's a regular file or not, so we skip it.
|
2315 |
+
# A regular file is always supposed to be have an
|
2316 |
+
# absolute path though.
|
2317 |
+
if path.startswith('/') and isfile_strict(path):
|
2318 |
+
# Get file position and flags.
|
2319 |
+
file = "%s/%s/fdinfo/%s" % (
|
2320 |
+
self._procfs_path,
|
2321 |
+
self.pid,
|
2322 |
+
fd,
|
2323 |
+
)
|
2324 |
+
try:
|
2325 |
+
with open_binary(file) as f:
|
2326 |
+
pos = int(f.readline().split()[1])
|
2327 |
+
flags = int(f.readline().split()[1], 8)
|
2328 |
+
except (FileNotFoundError, ProcessLookupError):
|
2329 |
+
# fd gone in the meantime; process may
|
2330 |
+
# still be alive
|
2331 |
+
hit_enoent = True
|
2332 |
+
else:
|
2333 |
+
mode = file_flags_to_mode(flags)
|
2334 |
+
ntuple = popenfile(
|
2335 |
+
path, int(fd), int(pos), mode, flags
|
2336 |
+
)
|
2337 |
+
retlist.append(ntuple)
|
2338 |
+
if hit_enoent:
|
2339 |
+
self._raise_if_not_alive()
|
2340 |
+
return retlist
|
2341 |
+
|
2342 |
+
@wrap_exceptions
|
2343 |
+
def connections(self, kind='inet'):
|
2344 |
+
ret = _connections.retrieve(kind, self.pid)
|
2345 |
+
self._raise_if_not_alive()
|
2346 |
+
return ret
|
2347 |
+
|
2348 |
+
@wrap_exceptions
|
2349 |
+
def num_fds(self):
|
2350 |
+
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
|
2351 |
+
|
2352 |
+
@wrap_exceptions
|
2353 |
+
def ppid(self):
|
2354 |
+
return int(self._parse_stat_file()['ppid'])
|
2355 |
+
|
2356 |
+
@wrap_exceptions
|
2357 |
+
def uids(self, _uids_re=re.compile(br'Uid:\t(\d+)\t(\d+)\t(\d+)')):
|
2358 |
+
data = self._read_status_file()
|
2359 |
+
real, effective, saved = _uids_re.findall(data)[0]
|
2360 |
+
return _common.puids(int(real), int(effective), int(saved))
|
2361 |
+
|
2362 |
+
@wrap_exceptions
|
2363 |
+
def gids(self, _gids_re=re.compile(br'Gid:\t(\d+)\t(\d+)\t(\d+)')):
|
2364 |
+
data = self._read_status_file()
|
2365 |
+
real, effective, saved = _gids_re.findall(data)[0]
|
2366 |
+
return _common.pgids(int(real), int(effective), int(saved))
|
env-llmeval/lib/python3.10/site-packages/psutil/_psosx.py
ADDED
@@ -0,0 +1,555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""macOS platform implementation."""
|
6 |
+
|
7 |
+
import errno
|
8 |
+
import functools
|
9 |
+
import os
|
10 |
+
from collections import namedtuple
|
11 |
+
|
12 |
+
from . import _common
|
13 |
+
from . import _psposix
|
14 |
+
from . import _psutil_osx as cext
|
15 |
+
from . import _psutil_posix as cext_posix
|
16 |
+
from ._common import AccessDenied
|
17 |
+
from ._common import NoSuchProcess
|
18 |
+
from ._common import ZombieProcess
|
19 |
+
from ._common import conn_tmap
|
20 |
+
from ._common import conn_to_ntuple
|
21 |
+
from ._common import isfile_strict
|
22 |
+
from ._common import memoize_when_activated
|
23 |
+
from ._common import parse_environ_block
|
24 |
+
from ._common import usage_percent
|
25 |
+
from ._compat import PermissionError
|
26 |
+
from ._compat import ProcessLookupError
|
27 |
+
|
28 |
+
|
29 |
+
__extra__all__ = []
|
30 |
+
|
31 |
+
|
32 |
+
# =====================================================================
|
33 |
+
# --- globals
|
34 |
+
# =====================================================================
|
35 |
+
|
36 |
+
|
37 |
+
PAGESIZE = cext_posix.getpagesize()
|
38 |
+
AF_LINK = cext_posix.AF_LINK
|
39 |
+
|
40 |
+
TCP_STATUSES = {
|
41 |
+
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
42 |
+
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
43 |
+
cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
|
44 |
+
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
45 |
+
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
46 |
+
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
47 |
+
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
48 |
+
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
49 |
+
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
50 |
+
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
51 |
+
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
52 |
+
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
53 |
+
}
|
54 |
+
|
55 |
+
PROC_STATUSES = {
|
56 |
+
cext.SIDL: _common.STATUS_IDLE,
|
57 |
+
cext.SRUN: _common.STATUS_RUNNING,
|
58 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
59 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
60 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
61 |
+
}
|
62 |
+
|
63 |
+
kinfo_proc_map = dict(
|
64 |
+
ppid=0,
|
65 |
+
ruid=1,
|
66 |
+
euid=2,
|
67 |
+
suid=3,
|
68 |
+
rgid=4,
|
69 |
+
egid=5,
|
70 |
+
sgid=6,
|
71 |
+
ttynr=7,
|
72 |
+
ctime=8,
|
73 |
+
status=9,
|
74 |
+
name=10,
|
75 |
+
)
|
76 |
+
|
77 |
+
pidtaskinfo_map = dict(
|
78 |
+
cpuutime=0,
|
79 |
+
cpustime=1,
|
80 |
+
rss=2,
|
81 |
+
vms=3,
|
82 |
+
pfaults=4,
|
83 |
+
pageins=5,
|
84 |
+
numthreads=6,
|
85 |
+
volctxsw=7,
|
86 |
+
)
|
87 |
+
|
88 |
+
|
89 |
+
# =====================================================================
|
90 |
+
# --- named tuples
|
91 |
+
# =====================================================================
|
92 |
+
|
93 |
+
|
94 |
+
# fmt: off
|
95 |
+
# psutil.cpu_times()
|
96 |
+
scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle'])
|
97 |
+
# psutil.virtual_memory()
|
98 |
+
svmem = namedtuple(
|
99 |
+
'svmem', ['total', 'available', 'percent', 'used', 'free',
|
100 |
+
'active', 'inactive', 'wired'])
|
101 |
+
# psutil.Process.memory_info()
|
102 |
+
pmem = namedtuple('pmem', ['rss', 'vms', 'pfaults', 'pageins'])
|
103 |
+
# psutil.Process.memory_full_info()
|
104 |
+
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
|
105 |
+
# fmt: on
|
106 |
+
|
107 |
+
|
108 |
+
# =====================================================================
|
109 |
+
# --- memory
|
110 |
+
# =====================================================================
|
111 |
+
|
112 |
+
|
113 |
+
def virtual_memory():
|
114 |
+
"""System virtual memory as a namedtuple."""
|
115 |
+
total, active, inactive, wired, free, speculative = cext.virtual_mem()
|
116 |
+
# This is how Zabbix calculate avail and used mem:
|
117 |
+
# https://github.com/zabbix/zabbix/blob/trunk/src/libs/zbxsysinfo/
|
118 |
+
# osx/memory.c
|
119 |
+
# Also see: https://github.com/giampaolo/psutil/issues/1277
|
120 |
+
avail = inactive + free
|
121 |
+
used = active + wired
|
122 |
+
# This is NOT how Zabbix calculates free mem but it matches "free"
|
123 |
+
# cmdline utility.
|
124 |
+
free -= speculative
|
125 |
+
percent = usage_percent((total - avail), total, round_=1)
|
126 |
+
return svmem(total, avail, percent, used, free, active, inactive, wired)
|
127 |
+
|
128 |
+
|
129 |
+
def swap_memory():
|
130 |
+
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
|
131 |
+
total, used, free, sin, sout = cext.swap_mem()
|
132 |
+
percent = usage_percent(used, total, round_=1)
|
133 |
+
return _common.sswap(total, used, free, percent, sin, sout)
|
134 |
+
|
135 |
+
|
136 |
+
# =====================================================================
|
137 |
+
# --- CPU
|
138 |
+
# =====================================================================
|
139 |
+
|
140 |
+
|
141 |
+
def cpu_times():
|
142 |
+
"""Return system CPU times as a namedtuple."""
|
143 |
+
user, nice, system, idle = cext.cpu_times()
|
144 |
+
return scputimes(user, nice, system, idle)
|
145 |
+
|
146 |
+
|
147 |
+
def per_cpu_times():
|
148 |
+
"""Return system CPU times as a named tuple."""
|
149 |
+
ret = []
|
150 |
+
for cpu_t in cext.per_cpu_times():
|
151 |
+
user, nice, system, idle = cpu_t
|
152 |
+
item = scputimes(user, nice, system, idle)
|
153 |
+
ret.append(item)
|
154 |
+
return ret
|
155 |
+
|
156 |
+
|
157 |
+
def cpu_count_logical():
|
158 |
+
"""Return the number of logical CPUs in the system."""
|
159 |
+
return cext.cpu_count_logical()
|
160 |
+
|
161 |
+
|
162 |
+
def cpu_count_cores():
|
163 |
+
"""Return the number of CPU cores in the system."""
|
164 |
+
return cext.cpu_count_cores()
|
165 |
+
|
166 |
+
|
167 |
+
def cpu_stats():
|
168 |
+
ctx_switches, interrupts, soft_interrupts, syscalls, traps = (
|
169 |
+
cext.cpu_stats()
|
170 |
+
)
|
171 |
+
return _common.scpustats(
|
172 |
+
ctx_switches, interrupts, soft_interrupts, syscalls
|
173 |
+
)
|
174 |
+
|
175 |
+
|
176 |
+
def cpu_freq():
|
177 |
+
"""Return CPU frequency.
|
178 |
+
On macOS per-cpu frequency is not supported.
|
179 |
+
Also, the returned frequency never changes, see:
|
180 |
+
https://arstechnica.com/civis/viewtopic.php?f=19&t=465002.
|
181 |
+
"""
|
182 |
+
curr, min_, max_ = cext.cpu_freq()
|
183 |
+
return [_common.scpufreq(curr, min_, max_)]
|
184 |
+
|
185 |
+
|
186 |
+
# =====================================================================
|
187 |
+
# --- disks
|
188 |
+
# =====================================================================
|
189 |
+
|
190 |
+
|
191 |
+
disk_usage = _psposix.disk_usage
|
192 |
+
disk_io_counters = cext.disk_io_counters
|
193 |
+
|
194 |
+
|
195 |
+
def disk_partitions(all=False):
|
196 |
+
"""Return mounted disk partitions as a list of namedtuples."""
|
197 |
+
retlist = []
|
198 |
+
partitions = cext.disk_partitions()
|
199 |
+
for partition in partitions:
|
200 |
+
device, mountpoint, fstype, opts = partition
|
201 |
+
if device == 'none':
|
202 |
+
device = ''
|
203 |
+
if not all:
|
204 |
+
if not os.path.isabs(device) or not os.path.exists(device):
|
205 |
+
continue
|
206 |
+
maxfile = maxpath = None # set later
|
207 |
+
ntuple = _common.sdiskpart(
|
208 |
+
device, mountpoint, fstype, opts, maxfile, maxpath
|
209 |
+
)
|
210 |
+
retlist.append(ntuple)
|
211 |
+
return retlist
|
212 |
+
|
213 |
+
|
214 |
+
# =====================================================================
|
215 |
+
# --- sensors
|
216 |
+
# =====================================================================
|
217 |
+
|
218 |
+
|
219 |
+
def sensors_battery():
|
220 |
+
"""Return battery information."""
|
221 |
+
try:
|
222 |
+
percent, minsleft, power_plugged = cext.sensors_battery()
|
223 |
+
except NotImplementedError:
|
224 |
+
# no power source - return None according to interface
|
225 |
+
return None
|
226 |
+
power_plugged = power_plugged == 1
|
227 |
+
if power_plugged:
|
228 |
+
secsleft = _common.POWER_TIME_UNLIMITED
|
229 |
+
elif minsleft == -1:
|
230 |
+
secsleft = _common.POWER_TIME_UNKNOWN
|
231 |
+
else:
|
232 |
+
secsleft = minsleft * 60
|
233 |
+
return _common.sbattery(percent, secsleft, power_plugged)
|
234 |
+
|
235 |
+
|
236 |
+
# =====================================================================
|
237 |
+
# --- network
|
238 |
+
# =====================================================================
|
239 |
+
|
240 |
+
|
241 |
+
net_io_counters = cext.net_io_counters
|
242 |
+
net_if_addrs = cext_posix.net_if_addrs
|
243 |
+
|
244 |
+
|
245 |
+
def net_connections(kind='inet'):
|
246 |
+
"""System-wide network connections."""
|
247 |
+
# Note: on macOS this will fail with AccessDenied unless
|
248 |
+
# the process is owned by root.
|
249 |
+
ret = []
|
250 |
+
for pid in pids():
|
251 |
+
try:
|
252 |
+
cons = Process(pid).connections(kind)
|
253 |
+
except NoSuchProcess:
|
254 |
+
continue
|
255 |
+
else:
|
256 |
+
if cons:
|
257 |
+
for c in cons:
|
258 |
+
c = list(c) + [pid]
|
259 |
+
ret.append(_common.sconn(*c))
|
260 |
+
return ret
|
261 |
+
|
262 |
+
|
263 |
+
def net_if_stats():
|
264 |
+
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
265 |
+
names = net_io_counters().keys()
|
266 |
+
ret = {}
|
267 |
+
for name in names:
|
268 |
+
try:
|
269 |
+
mtu = cext_posix.net_if_mtu(name)
|
270 |
+
flags = cext_posix.net_if_flags(name)
|
271 |
+
duplex, speed = cext_posix.net_if_duplex_speed(name)
|
272 |
+
except OSError as err:
|
273 |
+
# https://github.com/giampaolo/psutil/issues/1279
|
274 |
+
if err.errno != errno.ENODEV:
|
275 |
+
raise
|
276 |
+
else:
|
277 |
+
if hasattr(_common, 'NicDuplex'):
|
278 |
+
duplex = _common.NicDuplex(duplex)
|
279 |
+
output_flags = ','.join(flags)
|
280 |
+
isup = 'running' in flags
|
281 |
+
ret[name] = _common.snicstats(
|
282 |
+
isup, duplex, speed, mtu, output_flags
|
283 |
+
)
|
284 |
+
return ret
|
285 |
+
|
286 |
+
|
287 |
+
# =====================================================================
|
288 |
+
# --- other system functions
|
289 |
+
# =====================================================================
|
290 |
+
|
291 |
+
|
292 |
+
def boot_time():
|
293 |
+
"""The system boot time expressed in seconds since the epoch."""
|
294 |
+
return cext.boot_time()
|
295 |
+
|
296 |
+
|
297 |
+
def users():
|
298 |
+
"""Return currently connected users as a list of namedtuples."""
|
299 |
+
retlist = []
|
300 |
+
rawlist = cext.users()
|
301 |
+
for item in rawlist:
|
302 |
+
user, tty, hostname, tstamp, pid = item
|
303 |
+
if tty == '~':
|
304 |
+
continue # reboot or shutdown
|
305 |
+
if not tstamp:
|
306 |
+
continue
|
307 |
+
nt = _common.suser(user, tty or None, hostname or None, tstamp, pid)
|
308 |
+
retlist.append(nt)
|
309 |
+
return retlist
|
310 |
+
|
311 |
+
|
312 |
+
# =====================================================================
|
313 |
+
# --- processes
|
314 |
+
# =====================================================================
|
315 |
+
|
316 |
+
|
317 |
+
def pids():
|
318 |
+
ls = cext.pids()
|
319 |
+
if 0 not in ls:
|
320 |
+
# On certain macOS versions pids() C doesn't return PID 0 but
|
321 |
+
# "ps" does and the process is querable via sysctl():
|
322 |
+
# https://travis-ci.org/giampaolo/psutil/jobs/309619941
|
323 |
+
try:
|
324 |
+
Process(0).create_time()
|
325 |
+
ls.insert(0, 0)
|
326 |
+
except NoSuchProcess:
|
327 |
+
pass
|
328 |
+
except AccessDenied:
|
329 |
+
ls.insert(0, 0)
|
330 |
+
return ls
|
331 |
+
|
332 |
+
|
333 |
+
pid_exists = _psposix.pid_exists
|
334 |
+
|
335 |
+
|
336 |
+
def is_zombie(pid):
|
337 |
+
try:
|
338 |
+
st = cext.proc_kinfo_oneshot(pid)[kinfo_proc_map['status']]
|
339 |
+
return st == cext.SZOMB
|
340 |
+
except OSError:
|
341 |
+
return False
|
342 |
+
|
343 |
+
|
344 |
+
def wrap_exceptions(fun):
|
345 |
+
"""Decorator which translates bare OSError exceptions into
|
346 |
+
NoSuchProcess and AccessDenied.
|
347 |
+
"""
|
348 |
+
|
349 |
+
@functools.wraps(fun)
|
350 |
+
def wrapper(self, *args, **kwargs):
|
351 |
+
try:
|
352 |
+
return fun(self, *args, **kwargs)
|
353 |
+
except ProcessLookupError:
|
354 |
+
if is_zombie(self.pid):
|
355 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
356 |
+
else:
|
357 |
+
raise NoSuchProcess(self.pid, self._name)
|
358 |
+
except PermissionError:
|
359 |
+
raise AccessDenied(self.pid, self._name)
|
360 |
+
|
361 |
+
return wrapper
|
362 |
+
|
363 |
+
|
364 |
+
class Process:
|
365 |
+
"""Wrapper class around underlying C implementation."""
|
366 |
+
|
367 |
+
__slots__ = ["pid", "_name", "_ppid", "_cache"]
|
368 |
+
|
369 |
+
def __init__(self, pid):
|
370 |
+
self.pid = pid
|
371 |
+
self._name = None
|
372 |
+
self._ppid = None
|
373 |
+
|
374 |
+
@wrap_exceptions
|
375 |
+
@memoize_when_activated
|
376 |
+
def _get_kinfo_proc(self):
|
377 |
+
# Note: should work with all PIDs without permission issues.
|
378 |
+
ret = cext.proc_kinfo_oneshot(self.pid)
|
379 |
+
assert len(ret) == len(kinfo_proc_map)
|
380 |
+
return ret
|
381 |
+
|
382 |
+
@wrap_exceptions
|
383 |
+
@memoize_when_activated
|
384 |
+
def _get_pidtaskinfo(self):
|
385 |
+
# Note: should work for PIDs owned by user only.
|
386 |
+
ret = cext.proc_pidtaskinfo_oneshot(self.pid)
|
387 |
+
assert len(ret) == len(pidtaskinfo_map)
|
388 |
+
return ret
|
389 |
+
|
390 |
+
def oneshot_enter(self):
|
391 |
+
self._get_kinfo_proc.cache_activate(self)
|
392 |
+
self._get_pidtaskinfo.cache_activate(self)
|
393 |
+
|
394 |
+
def oneshot_exit(self):
|
395 |
+
self._get_kinfo_proc.cache_deactivate(self)
|
396 |
+
self._get_pidtaskinfo.cache_deactivate(self)
|
397 |
+
|
398 |
+
@wrap_exceptions
|
399 |
+
def name(self):
|
400 |
+
name = self._get_kinfo_proc()[kinfo_proc_map['name']]
|
401 |
+
return name if name is not None else cext.proc_name(self.pid)
|
402 |
+
|
403 |
+
@wrap_exceptions
|
404 |
+
def exe(self):
|
405 |
+
return cext.proc_exe(self.pid)
|
406 |
+
|
407 |
+
@wrap_exceptions
|
408 |
+
def cmdline(self):
|
409 |
+
return cext.proc_cmdline(self.pid)
|
410 |
+
|
411 |
+
@wrap_exceptions
|
412 |
+
def environ(self):
|
413 |
+
return parse_environ_block(cext.proc_environ(self.pid))
|
414 |
+
|
415 |
+
@wrap_exceptions
|
416 |
+
def ppid(self):
|
417 |
+
self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']]
|
418 |
+
return self._ppid
|
419 |
+
|
420 |
+
@wrap_exceptions
|
421 |
+
def cwd(self):
|
422 |
+
return cext.proc_cwd(self.pid)
|
423 |
+
|
424 |
+
@wrap_exceptions
|
425 |
+
def uids(self):
|
426 |
+
rawtuple = self._get_kinfo_proc()
|
427 |
+
return _common.puids(
|
428 |
+
rawtuple[kinfo_proc_map['ruid']],
|
429 |
+
rawtuple[kinfo_proc_map['euid']],
|
430 |
+
rawtuple[kinfo_proc_map['suid']],
|
431 |
+
)
|
432 |
+
|
433 |
+
@wrap_exceptions
|
434 |
+
def gids(self):
|
435 |
+
rawtuple = self._get_kinfo_proc()
|
436 |
+
return _common.puids(
|
437 |
+
rawtuple[kinfo_proc_map['rgid']],
|
438 |
+
rawtuple[kinfo_proc_map['egid']],
|
439 |
+
rawtuple[kinfo_proc_map['sgid']],
|
440 |
+
)
|
441 |
+
|
442 |
+
@wrap_exceptions
|
443 |
+
def terminal(self):
|
444 |
+
tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']]
|
445 |
+
tmap = _psposix.get_terminal_map()
|
446 |
+
try:
|
447 |
+
return tmap[tty_nr]
|
448 |
+
except KeyError:
|
449 |
+
return None
|
450 |
+
|
451 |
+
@wrap_exceptions
|
452 |
+
def memory_info(self):
|
453 |
+
rawtuple = self._get_pidtaskinfo()
|
454 |
+
return pmem(
|
455 |
+
rawtuple[pidtaskinfo_map['rss']],
|
456 |
+
rawtuple[pidtaskinfo_map['vms']],
|
457 |
+
rawtuple[pidtaskinfo_map['pfaults']],
|
458 |
+
rawtuple[pidtaskinfo_map['pageins']],
|
459 |
+
)
|
460 |
+
|
461 |
+
@wrap_exceptions
|
462 |
+
def memory_full_info(self):
|
463 |
+
basic_mem = self.memory_info()
|
464 |
+
uss = cext.proc_memory_uss(self.pid)
|
465 |
+
return pfullmem(*basic_mem + (uss,))
|
466 |
+
|
467 |
+
@wrap_exceptions
|
468 |
+
def cpu_times(self):
|
469 |
+
rawtuple = self._get_pidtaskinfo()
|
470 |
+
return _common.pcputimes(
|
471 |
+
rawtuple[pidtaskinfo_map['cpuutime']],
|
472 |
+
rawtuple[pidtaskinfo_map['cpustime']],
|
473 |
+
# children user / system times are not retrievable (set to 0)
|
474 |
+
0.0,
|
475 |
+
0.0,
|
476 |
+
)
|
477 |
+
|
478 |
+
@wrap_exceptions
|
479 |
+
def create_time(self):
|
480 |
+
return self._get_kinfo_proc()[kinfo_proc_map['ctime']]
|
481 |
+
|
482 |
+
@wrap_exceptions
|
483 |
+
def num_ctx_switches(self):
|
484 |
+
# Unvoluntary value seems not to be available;
|
485 |
+
# getrusage() numbers seems to confirm this theory.
|
486 |
+
# We set it to 0.
|
487 |
+
vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']]
|
488 |
+
return _common.pctxsw(vol, 0)
|
489 |
+
|
490 |
+
@wrap_exceptions
|
491 |
+
def num_threads(self):
|
492 |
+
return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']]
|
493 |
+
|
494 |
+
@wrap_exceptions
|
495 |
+
def open_files(self):
|
496 |
+
if self.pid == 0:
|
497 |
+
return []
|
498 |
+
files = []
|
499 |
+
rawlist = cext.proc_open_files(self.pid)
|
500 |
+
for path, fd in rawlist:
|
501 |
+
if isfile_strict(path):
|
502 |
+
ntuple = _common.popenfile(path, fd)
|
503 |
+
files.append(ntuple)
|
504 |
+
return files
|
505 |
+
|
506 |
+
@wrap_exceptions
|
507 |
+
def connections(self, kind='inet'):
|
508 |
+
if kind not in conn_tmap:
|
509 |
+
raise ValueError(
|
510 |
+
"invalid %r kind argument; choose between %s"
|
511 |
+
% (kind, ', '.join([repr(x) for x in conn_tmap]))
|
512 |
+
)
|
513 |
+
families, types = conn_tmap[kind]
|
514 |
+
rawlist = cext.proc_connections(self.pid, families, types)
|
515 |
+
ret = []
|
516 |
+
for item in rawlist:
|
517 |
+
fd, fam, type, laddr, raddr, status = item
|
518 |
+
nt = conn_to_ntuple(
|
519 |
+
fd, fam, type, laddr, raddr, status, TCP_STATUSES
|
520 |
+
)
|
521 |
+
ret.append(nt)
|
522 |
+
return ret
|
523 |
+
|
524 |
+
@wrap_exceptions
|
525 |
+
def num_fds(self):
|
526 |
+
if self.pid == 0:
|
527 |
+
return 0
|
528 |
+
return cext.proc_num_fds(self.pid)
|
529 |
+
|
530 |
+
@wrap_exceptions
|
531 |
+
def wait(self, timeout=None):
|
532 |
+
return _psposix.wait_pid(self.pid, timeout, self._name)
|
533 |
+
|
534 |
+
@wrap_exceptions
|
535 |
+
def nice_get(self):
|
536 |
+
return cext_posix.getpriority(self.pid)
|
537 |
+
|
538 |
+
@wrap_exceptions
|
539 |
+
def nice_set(self, value):
|
540 |
+
return cext_posix.setpriority(self.pid, value)
|
541 |
+
|
542 |
+
@wrap_exceptions
|
543 |
+
def status(self):
|
544 |
+
code = self._get_kinfo_proc()[kinfo_proc_map['status']]
|
545 |
+
# XXX is '?' legit? (we're not supposed to return it anyway)
|
546 |
+
return PROC_STATUSES.get(code, '?')
|
547 |
+
|
548 |
+
@wrap_exceptions
|
549 |
+
def threads(self):
|
550 |
+
rawlist = cext.proc_threads(self.pid)
|
551 |
+
retlist = []
|
552 |
+
for thread_id, utime, stime in rawlist:
|
553 |
+
ntuple = _common.pthread(thread_id, utime, stime)
|
554 |
+
retlist.append(ntuple)
|
555 |
+
return retlist
|
env-llmeval/lib/python3.10/site-packages/psutil/_psposix.py
ADDED
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""Routines common to all posix systems."""
|
6 |
+
|
7 |
+
import glob
|
8 |
+
import os
|
9 |
+
import signal
|
10 |
+
import sys
|
11 |
+
import time
|
12 |
+
|
13 |
+
from ._common import MACOS
|
14 |
+
from ._common import TimeoutExpired
|
15 |
+
from ._common import memoize
|
16 |
+
from ._common import sdiskusage
|
17 |
+
from ._common import usage_percent
|
18 |
+
from ._compat import PY3
|
19 |
+
from ._compat import ChildProcessError
|
20 |
+
from ._compat import FileNotFoundError
|
21 |
+
from ._compat import InterruptedError
|
22 |
+
from ._compat import PermissionError
|
23 |
+
from ._compat import ProcessLookupError
|
24 |
+
from ._compat import unicode
|
25 |
+
|
26 |
+
|
27 |
+
if MACOS:
|
28 |
+
from . import _psutil_osx
|
29 |
+
|
30 |
+
|
31 |
+
if PY3:
|
32 |
+
import enum
|
33 |
+
else:
|
34 |
+
enum = None
|
35 |
+
|
36 |
+
|
37 |
+
__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map']
|
38 |
+
|
39 |
+
|
40 |
+
def pid_exists(pid):
|
41 |
+
"""Check whether pid exists in the current process table."""
|
42 |
+
if pid == 0:
|
43 |
+
# According to "man 2 kill" PID 0 has a special meaning:
|
44 |
+
# it refers to <<every process in the process group of the
|
45 |
+
# calling process>> so we don't want to go any further.
|
46 |
+
# If we get here it means this UNIX platform *does* have
|
47 |
+
# a process with id 0.
|
48 |
+
return True
|
49 |
+
try:
|
50 |
+
os.kill(pid, 0)
|
51 |
+
except ProcessLookupError:
|
52 |
+
return False
|
53 |
+
except PermissionError:
|
54 |
+
# EPERM clearly means there's a process to deny access to
|
55 |
+
return True
|
56 |
+
# According to "man 2 kill" possible error values are
|
57 |
+
# (EINVAL, EPERM, ESRCH)
|
58 |
+
else:
|
59 |
+
return True
|
60 |
+
|
61 |
+
|
62 |
+
# Python 3.5 signals enum (contributed by me ^^):
|
63 |
+
# https://bugs.python.org/issue21076
|
64 |
+
if enum is not None and hasattr(signal, "Signals"):
|
65 |
+
Negsignal = enum.IntEnum(
|
66 |
+
'Negsignal', dict([(x.name, -x.value) for x in signal.Signals])
|
67 |
+
)
|
68 |
+
|
69 |
+
def negsig_to_enum(num):
|
70 |
+
"""Convert a negative signal value to an enum."""
|
71 |
+
try:
|
72 |
+
return Negsignal(num)
|
73 |
+
except ValueError:
|
74 |
+
return num
|
75 |
+
|
76 |
+
else: # pragma: no cover
|
77 |
+
|
78 |
+
def negsig_to_enum(num):
|
79 |
+
return num
|
80 |
+
|
81 |
+
|
82 |
+
def wait_pid(
|
83 |
+
pid,
|
84 |
+
timeout=None,
|
85 |
+
proc_name=None,
|
86 |
+
_waitpid=os.waitpid,
|
87 |
+
_timer=getattr(time, 'monotonic', time.time), # noqa: B008
|
88 |
+
_min=min,
|
89 |
+
_sleep=time.sleep,
|
90 |
+
_pid_exists=pid_exists,
|
91 |
+
):
|
92 |
+
"""Wait for a process PID to terminate.
|
93 |
+
|
94 |
+
If the process terminated normally by calling exit(3) or _exit(2),
|
95 |
+
or by returning from main(), the return value is the positive integer
|
96 |
+
passed to *exit().
|
97 |
+
|
98 |
+
If it was terminated by a signal it returns the negated value of the
|
99 |
+
signal which caused the termination (e.g. -SIGTERM).
|
100 |
+
|
101 |
+
If PID is not a children of os.getpid() (current process) just
|
102 |
+
wait until the process disappears and return None.
|
103 |
+
|
104 |
+
If PID does not exist at all return None immediately.
|
105 |
+
|
106 |
+
If *timeout* != None and process is still alive raise TimeoutExpired.
|
107 |
+
timeout=0 is also possible (either return immediately or raise).
|
108 |
+
"""
|
109 |
+
if pid <= 0:
|
110 |
+
# see "man waitpid"
|
111 |
+
msg = "can't wait for PID 0"
|
112 |
+
raise ValueError(msg)
|
113 |
+
interval = 0.0001
|
114 |
+
flags = 0
|
115 |
+
if timeout is not None:
|
116 |
+
flags |= os.WNOHANG
|
117 |
+
stop_at = _timer() + timeout
|
118 |
+
|
119 |
+
def sleep(interval):
|
120 |
+
# Sleep for some time and return a new increased interval.
|
121 |
+
if timeout is not None:
|
122 |
+
if _timer() >= stop_at:
|
123 |
+
raise TimeoutExpired(timeout, pid=pid, name=proc_name)
|
124 |
+
_sleep(interval)
|
125 |
+
return _min(interval * 2, 0.04)
|
126 |
+
|
127 |
+
# See: https://linux.die.net/man/2/waitpid
|
128 |
+
while True:
|
129 |
+
try:
|
130 |
+
retpid, status = os.waitpid(pid, flags)
|
131 |
+
except InterruptedError:
|
132 |
+
interval = sleep(interval)
|
133 |
+
except ChildProcessError:
|
134 |
+
# This has two meanings:
|
135 |
+
# - PID is not a child of os.getpid() in which case
|
136 |
+
# we keep polling until it's gone
|
137 |
+
# - PID never existed in the first place
|
138 |
+
# In both cases we'll eventually return None as we
|
139 |
+
# can't determine its exit status code.
|
140 |
+
while _pid_exists(pid):
|
141 |
+
interval = sleep(interval)
|
142 |
+
return
|
143 |
+
else:
|
144 |
+
if retpid == 0:
|
145 |
+
# WNOHANG flag was used and PID is still running.
|
146 |
+
interval = sleep(interval)
|
147 |
+
continue
|
148 |
+
|
149 |
+
if os.WIFEXITED(status):
|
150 |
+
# Process terminated normally by calling exit(3) or _exit(2),
|
151 |
+
# or by returning from main(). The return value is the
|
152 |
+
# positive integer passed to *exit().
|
153 |
+
return os.WEXITSTATUS(status)
|
154 |
+
elif os.WIFSIGNALED(status):
|
155 |
+
# Process exited due to a signal. Return the negative value
|
156 |
+
# of that signal.
|
157 |
+
return negsig_to_enum(-os.WTERMSIG(status))
|
158 |
+
# elif os.WIFSTOPPED(status):
|
159 |
+
# # Process was stopped via SIGSTOP or is being traced, and
|
160 |
+
# # waitpid() was called with WUNTRACED flag. PID is still
|
161 |
+
# # alive. From now on waitpid() will keep returning (0, 0)
|
162 |
+
# # until the process state doesn't change.
|
163 |
+
# # It may make sense to catch/enable this since stopped PIDs
|
164 |
+
# # ignore SIGTERM.
|
165 |
+
# interval = sleep(interval)
|
166 |
+
# continue
|
167 |
+
# elif os.WIFCONTINUED(status):
|
168 |
+
# # Process was resumed via SIGCONT and waitpid() was called
|
169 |
+
# # with WCONTINUED flag.
|
170 |
+
# interval = sleep(interval)
|
171 |
+
# continue
|
172 |
+
else:
|
173 |
+
# Should never happen.
|
174 |
+
raise ValueError("unknown process exit status %r" % status)
|
175 |
+
|
176 |
+
|
177 |
+
def disk_usage(path):
|
178 |
+
"""Return disk usage associated with path.
|
179 |
+
Note: UNIX usually reserves 5% disk space which is not accessible
|
180 |
+
by user. In this function "total" and "used" values reflect the
|
181 |
+
total and used disk space whereas "free" and "percent" represent
|
182 |
+
the "free" and "used percent" user disk space.
|
183 |
+
"""
|
184 |
+
if PY3:
|
185 |
+
st = os.statvfs(path)
|
186 |
+
else: # pragma: no cover
|
187 |
+
# os.statvfs() does not support unicode on Python 2:
|
188 |
+
# - https://github.com/giampaolo/psutil/issues/416
|
189 |
+
# - http://bugs.python.org/issue18695
|
190 |
+
try:
|
191 |
+
st = os.statvfs(path)
|
192 |
+
except UnicodeEncodeError:
|
193 |
+
if isinstance(path, unicode):
|
194 |
+
try:
|
195 |
+
path = path.encode(sys.getfilesystemencoding())
|
196 |
+
except UnicodeEncodeError:
|
197 |
+
pass
|
198 |
+
st = os.statvfs(path)
|
199 |
+
else:
|
200 |
+
raise
|
201 |
+
|
202 |
+
# Total space which is only available to root (unless changed
|
203 |
+
# at system level).
|
204 |
+
total = st.f_blocks * st.f_frsize
|
205 |
+
# Remaining free space usable by root.
|
206 |
+
avail_to_root = st.f_bfree * st.f_frsize
|
207 |
+
# Remaining free space usable by user.
|
208 |
+
avail_to_user = st.f_bavail * st.f_frsize
|
209 |
+
# Total space being used in general.
|
210 |
+
used = total - avail_to_root
|
211 |
+
if MACOS:
|
212 |
+
# see: https://github.com/giampaolo/psutil/pull/2152
|
213 |
+
used = _psutil_osx.disk_usage_used(path, used)
|
214 |
+
# Total space which is available to user (same as 'total' but
|
215 |
+
# for the user).
|
216 |
+
total_user = used + avail_to_user
|
217 |
+
# User usage percent compared to the total amount of space
|
218 |
+
# the user can use. This number would be higher if compared
|
219 |
+
# to root's because the user has less space (usually -5%).
|
220 |
+
usage_percent_user = usage_percent(used, total_user, round_=1)
|
221 |
+
|
222 |
+
# NB: the percentage is -5% than what shown by df due to
|
223 |
+
# reserved blocks that we are currently not considering:
|
224 |
+
# https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462
|
225 |
+
return sdiskusage(
|
226 |
+
total=total, used=used, free=avail_to_user, percent=usage_percent_user
|
227 |
+
)
|
228 |
+
|
229 |
+
|
230 |
+
@memoize
|
231 |
+
def get_terminal_map():
|
232 |
+
"""Get a map of device-id -> path as a dict.
|
233 |
+
Used by Process.terminal().
|
234 |
+
"""
|
235 |
+
ret = {}
|
236 |
+
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
|
237 |
+
for name in ls:
|
238 |
+
assert name not in ret, name
|
239 |
+
try:
|
240 |
+
ret[os.stat(name).st_rdev] = name
|
241 |
+
except FileNotFoundError:
|
242 |
+
p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
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""Sun OS Solaris platform implementation."""
|
6 |
+
|
7 |
+
import errno
|
8 |
+
import functools
|
9 |
+
import os
|
10 |
+
import socket
|
11 |
+
import subprocess
|
12 |
+
import sys
|
13 |
+
from collections import namedtuple
|
14 |
+
from socket import AF_INET
|
15 |
+
|
16 |
+
from . import _common
|
17 |
+
from . import _psposix
|
18 |
+
from . import _psutil_posix as cext_posix
|
19 |
+
from . import _psutil_sunos as cext
|
20 |
+
from ._common import AF_INET6
|
21 |
+
from ._common import AccessDenied
|
22 |
+
from ._common import NoSuchProcess
|
23 |
+
from ._common import ZombieProcess
|
24 |
+
from ._common import debug
|
25 |
+
from ._common import get_procfs_path
|
26 |
+
from ._common import isfile_strict
|
27 |
+
from ._common import memoize_when_activated
|
28 |
+
from ._common import sockfam_to_enum
|
29 |
+
from ._common import socktype_to_enum
|
30 |
+
from ._common import usage_percent
|
31 |
+
from ._compat import PY3
|
32 |
+
from ._compat import FileNotFoundError
|
33 |
+
from ._compat import PermissionError
|
34 |
+
from ._compat import ProcessLookupError
|
35 |
+
from ._compat import b
|
36 |
+
|
37 |
+
|
38 |
+
__extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"]
|
39 |
+
|
40 |
+
|
41 |
+
# =====================================================================
|
42 |
+
# --- globals
|
43 |
+
# =====================================================================
|
44 |
+
|
45 |
+
|
46 |
+
PAGE_SIZE = cext_posix.getpagesize()
|
47 |
+
AF_LINK = cext_posix.AF_LINK
|
48 |
+
IS_64_BIT = sys.maxsize > 2**32
|
49 |
+
|
50 |
+
CONN_IDLE = "IDLE"
|
51 |
+
CONN_BOUND = "BOUND"
|
52 |
+
|
53 |
+
PROC_STATUSES = {
|
54 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
55 |
+
cext.SRUN: _common.STATUS_RUNNING,
|
56 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
57 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
58 |
+
cext.SIDL: _common.STATUS_IDLE,
|
59 |
+
cext.SONPROC: _common.STATUS_RUNNING, # same as run
|
60 |
+
cext.SWAIT: _common.STATUS_WAITING,
|
61 |
+
}
|
62 |
+
|
63 |
+
TCP_STATUSES = {
|
64 |
+
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
65 |
+
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
66 |
+
cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
|
67 |
+
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
68 |
+
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
69 |
+
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
70 |
+
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
71 |
+
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
72 |
+
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
73 |
+
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
74 |
+
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
75 |
+
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
76 |
+
cext.TCPS_IDLE: CONN_IDLE, # sunos specific
|
77 |
+
cext.TCPS_BOUND: CONN_BOUND, # sunos specific
|
78 |
+
}
|
79 |
+
|
80 |
+
proc_info_map = dict(
|
81 |
+
ppid=0,
|
82 |
+
rss=1,
|
83 |
+
vms=2,
|
84 |
+
create_time=3,
|
85 |
+
nice=4,
|
86 |
+
num_threads=5,
|
87 |
+
status=6,
|
88 |
+
ttynr=7,
|
89 |
+
uid=8,
|
90 |
+
euid=9,
|
91 |
+
gid=10,
|
92 |
+
egid=11,
|
93 |
+
)
|
94 |
+
|
95 |
+
|
96 |
+
# =====================================================================
|
97 |
+
# --- named tuples
|
98 |
+
# =====================================================================
|
99 |
+
|
100 |
+
|
101 |
+
# psutil.cpu_times()
|
102 |
+
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
|
103 |
+
# psutil.cpu_times(percpu=True)
|
104 |
+
pcputimes = namedtuple(
|
105 |
+
'pcputimes', ['user', 'system', 'children_user', 'children_system']
|
106 |
+
)
|
107 |
+
# psutil.virtual_memory()
|
108 |
+
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
|
109 |
+
# psutil.Process.memory_info()
|
110 |
+
pmem = namedtuple('pmem', ['rss', 'vms'])
|
111 |
+
pfullmem = pmem
|
112 |
+
# psutil.Process.memory_maps(grouped=True)
|
113 |
+
pmmap_grouped = namedtuple(
|
114 |
+
'pmmap_grouped', ['path', 'rss', 'anonymous', 'locked']
|
115 |
+
)
|
116 |
+
# psutil.Process.memory_maps(grouped=False)
|
117 |
+
pmmap_ext = namedtuple(
|
118 |
+
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields)
|
119 |
+
)
|
120 |
+
|
121 |
+
|
122 |
+
# =====================================================================
|
123 |
+
# --- memory
|
124 |
+
# =====================================================================
|
125 |
+
|
126 |
+
|
127 |
+
def virtual_memory():
|
128 |
+
"""Report virtual memory metrics."""
|
129 |
+
# we could have done this with kstat, but IMHO this is good enough
|
130 |
+
total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
|
131 |
+
# note: there's no difference on Solaris
|
132 |
+
free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE
|
133 |
+
used = total - free
|
134 |
+
percent = usage_percent(used, total, round_=1)
|
135 |
+
return svmem(total, avail, percent, used, free)
|
136 |
+
|
137 |
+
|
138 |
+
def swap_memory():
|
139 |
+
"""Report swap memory metrics."""
|
140 |
+
sin, sout = cext.swap_mem()
|
141 |
+
# XXX
|
142 |
+
# we are supposed to get total/free by doing so:
|
143 |
+
# http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/
|
144 |
+
# usr/src/cmd/swap/swap.c
|
145 |
+
# ...nevertheless I can't manage to obtain the same numbers as 'swap'
|
146 |
+
# cmdline utility, so let's parse its output (sigh!)
|
147 |
+
p = subprocess.Popen(
|
148 |
+
[
|
149 |
+
'/usr/bin/env',
|
150 |
+
'PATH=/usr/sbin:/sbin:%s' % os.environ['PATH'],
|
151 |
+
'swap',
|
152 |
+
'-l',
|
153 |
+
],
|
154 |
+
stdout=subprocess.PIPE,
|
155 |
+
)
|
156 |
+
stdout, _ = p.communicate()
|
157 |
+
if PY3:
|
158 |
+
stdout = stdout.decode(sys.stdout.encoding)
|
159 |
+
if p.returncode != 0:
|
160 |
+
raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode)
|
161 |
+
|
162 |
+
lines = stdout.strip().split('\n')[1:]
|
163 |
+
if not lines:
|
164 |
+
msg = 'no swap device(s) configured'
|
165 |
+
raise RuntimeError(msg)
|
166 |
+
total = free = 0
|
167 |
+
for line in lines:
|
168 |
+
line = line.split()
|
169 |
+
t, f = line[3:5]
|
170 |
+
total += int(int(t) * 512)
|
171 |
+
free += int(int(f) * 512)
|
172 |
+
used = total - free
|
173 |
+
percent = usage_percent(used, total, round_=1)
|
174 |
+
return _common.sswap(
|
175 |
+
total, used, free, percent, sin * PAGE_SIZE, sout * PAGE_SIZE
|
176 |
+
)
|
177 |
+
|
178 |
+
|
179 |
+
# =====================================================================
|
180 |
+
# --- CPU
|
181 |
+
# =====================================================================
|
182 |
+
|
183 |
+
|
184 |
+
def cpu_times():
|
185 |
+
"""Return system-wide CPU times as a named tuple."""
|
186 |
+
ret = cext.per_cpu_times()
|
187 |
+
return scputimes(*[sum(x) for x in zip(*ret)])
|
188 |
+
|
189 |
+
|
190 |
+
def per_cpu_times():
|
191 |
+
"""Return system per-CPU times as a list of named tuples."""
|
192 |
+
ret = cext.per_cpu_times()
|
193 |
+
return [scputimes(*x) for x in ret]
|
194 |
+
|
195 |
+
|
196 |
+
def cpu_count_logical():
|
197 |
+
"""Return the number of logical CPUs in the system."""
|
198 |
+
try:
|
199 |
+
return os.sysconf("SC_NPROCESSORS_ONLN")
|
200 |
+
except ValueError:
|
201 |
+
# mimic os.cpu_count() behavior
|
202 |
+
return None
|
203 |
+
|
204 |
+
|
205 |
+
def cpu_count_cores():
|
206 |
+
"""Return the number of CPU cores in the system."""
|
207 |
+
return cext.cpu_count_cores()
|
208 |
+
|
209 |
+
|
210 |
+
def cpu_stats():
|
211 |
+
"""Return various CPU stats as a named tuple."""
|
212 |
+
ctx_switches, interrupts, syscalls, traps = cext.cpu_stats()
|
213 |
+
soft_interrupts = 0
|
214 |
+
return _common.scpustats(
|
215 |
+
ctx_switches, interrupts, soft_interrupts, syscalls
|
216 |
+
)
|
217 |
+
|
218 |
+
|
219 |
+
# =====================================================================
|
220 |
+
# --- disks
|
221 |
+
# =====================================================================
|
222 |
+
|
223 |
+
|
224 |
+
disk_io_counters = cext.disk_io_counters
|
225 |
+
disk_usage = _psposix.disk_usage
|
226 |
+
|
227 |
+
|
228 |
+
def disk_partitions(all=False):
|
229 |
+
"""Return system disk partitions."""
|
230 |
+
# TODO - the filtering logic should be better checked so that
|
231 |
+
# it tries to reflect 'df' as much as possible
|
232 |
+
retlist = []
|
233 |
+
partitions = cext.disk_partitions()
|
234 |
+
for partition in partitions:
|
235 |
+
device, mountpoint, fstype, opts = partition
|
236 |
+
if device == 'none':
|
237 |
+
device = ''
|
238 |
+
if not all:
|
239 |
+
# Differently from, say, Linux, we don't have a list of
|
240 |
+
# common fs types so the best we can do, AFAIK, is to
|
241 |
+
# filter by filesystem having a total size > 0.
|
242 |
+
try:
|
243 |
+
if not disk_usage(mountpoint).total:
|
244 |
+
continue
|
245 |
+
except OSError as err:
|
246 |
+
# https://github.com/giampaolo/psutil/issues/1674
|
247 |
+
debug("skipping %r: %s" % (mountpoint, err))
|
248 |
+
continue
|
249 |
+
maxfile = maxpath = None # set later
|
250 |
+
ntuple = _common.sdiskpart(
|
251 |
+
device, mountpoint, fstype, opts, maxfile, maxpath
|
252 |
+
)
|
253 |
+
retlist.append(ntuple)
|
254 |
+
return retlist
|
255 |
+
|
256 |
+
|
257 |
+
# =====================================================================
|
258 |
+
# --- network
|
259 |
+
# =====================================================================
|
260 |
+
|
261 |
+
|
262 |
+
net_io_counters = cext.net_io_counters
|
263 |
+
net_if_addrs = cext_posix.net_if_addrs
|
264 |
+
|
265 |
+
|
266 |
+
def net_connections(kind, _pid=-1):
|
267 |
+
"""Return socket connections. If pid == -1 return system-wide
|
268 |
+
connections (as opposed to connections opened by one process only).
|
269 |
+
Only INET sockets are returned (UNIX are not).
|
270 |
+
"""
|
271 |
+
cmap = _common.conn_tmap.copy()
|
272 |
+
if _pid == -1:
|
273 |
+
cmap.pop('unix', 0)
|
274 |
+
if kind not in cmap:
|
275 |
+
raise ValueError(
|
276 |
+
"invalid %r kind argument; choose between %s"
|
277 |
+
% (kind, ', '.join([repr(x) for x in cmap]))
|
278 |
+
)
|
279 |
+
families, types = _common.conn_tmap[kind]
|
280 |
+
rawlist = cext.net_connections(_pid)
|
281 |
+
ret = set()
|
282 |
+
for item in rawlist:
|
283 |
+
fd, fam, type_, laddr, raddr, status, pid = item
|
284 |
+
if fam not in families:
|
285 |
+
continue
|
286 |
+
if type_ not in types:
|
287 |
+
continue
|
288 |
+
# TODO: refactor and use _common.conn_to_ntuple.
|
289 |
+
if fam in (AF_INET, AF_INET6):
|
290 |
+
if laddr:
|
291 |
+
laddr = _common.addr(*laddr)
|
292 |
+
if raddr:
|
293 |
+
raddr = _common.addr(*raddr)
|
294 |
+
status = TCP_STATUSES[status]
|
295 |
+
fam = sockfam_to_enum(fam)
|
296 |
+
type_ = socktype_to_enum(type_)
|
297 |
+
if _pid == -1:
|
298 |
+
nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid)
|
299 |
+
else:
|
300 |
+
nt = _common.pconn(fd, fam, type_, laddr, raddr, status)
|
301 |
+
ret.add(nt)
|
302 |
+
return list(ret)
|
303 |
+
|
304 |
+
|
305 |
+
def net_if_stats():
|
306 |
+
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
307 |
+
ret = cext.net_if_stats()
|
308 |
+
for name, items in ret.items():
|
309 |
+
isup, duplex, speed, mtu = items
|
310 |
+
if hasattr(_common, 'NicDuplex'):
|
311 |
+
duplex = _common.NicDuplex(duplex)
|
312 |
+
ret[name] = _common.snicstats(isup, duplex, speed, mtu, '')
|
313 |
+
return ret
|
314 |
+
|
315 |
+
|
316 |
+
# =====================================================================
|
317 |
+
# --- other system functions
|
318 |
+
# =====================================================================
|
319 |
+
|
320 |
+
|
321 |
+
def boot_time():
|
322 |
+
"""The system boot time expressed in seconds since the epoch."""
|
323 |
+
return cext.boot_time()
|
324 |
+
|
325 |
+
|
326 |
+
def users():
|
327 |
+
"""Return currently connected users as a list of namedtuples."""
|
328 |
+
retlist = []
|
329 |
+
rawlist = cext.users()
|
330 |
+
localhost = (':0.0', ':0')
|
331 |
+
for item in rawlist:
|
332 |
+
user, tty, hostname, tstamp, user_process, pid = item
|
333 |
+
# note: the underlying C function includes entries about
|
334 |
+
# system boot, run level and others. We might want
|
335 |
+
# to use them in the future.
|
336 |
+
if not user_process:
|
337 |
+
continue
|
338 |
+
if hostname in localhost:
|
339 |
+
hostname = 'localhost'
|
340 |
+
nt = _common.suser(user, tty, hostname, tstamp, pid)
|
341 |
+
retlist.append(nt)
|
342 |
+
return retlist
|
343 |
+
|
344 |
+
|
345 |
+
# =====================================================================
|
346 |
+
# --- processes
|
347 |
+
# =====================================================================
|
348 |
+
|
349 |
+
|
350 |
+
def pids():
|
351 |
+
"""Returns a list of PIDs currently running on the system."""
|
352 |
+
return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
|
353 |
+
|
354 |
+
|
355 |
+
def pid_exists(pid):
|
356 |
+
"""Check for the existence of a unix pid."""
|
357 |
+
return _psposix.pid_exists(pid)
|
358 |
+
|
359 |
+
|
360 |
+
def wrap_exceptions(fun):
|
361 |
+
"""Call callable into a try/except clause and translate ENOENT,
|
362 |
+
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
|
363 |
+
"""
|
364 |
+
|
365 |
+
@functools.wraps(fun)
|
366 |
+
def wrapper(self, *args, **kwargs):
|
367 |
+
try:
|
368 |
+
return fun(self, *args, **kwargs)
|
369 |
+
except (FileNotFoundError, ProcessLookupError):
|
370 |
+
# ENOENT (no such file or directory) gets raised on open().
|
371 |
+
# ESRCH (no such process) can get raised on read() if
|
372 |
+
# process is gone in meantime.
|
373 |
+
if not pid_exists(self.pid):
|
374 |
+
raise NoSuchProcess(self.pid, self._name)
|
375 |
+
else:
|
376 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
377 |
+
except PermissionError:
|
378 |
+
raise AccessDenied(self.pid, self._name)
|
379 |
+
except OSError:
|
380 |
+
if self.pid == 0:
|
381 |
+
if 0 in pids():
|
382 |
+
raise AccessDenied(self.pid, self._name)
|
383 |
+
else:
|
384 |
+
raise
|
385 |
+
raise
|
386 |
+
|
387 |
+
return wrapper
|
388 |
+
|
389 |
+
|
390 |
+
class Process:
|
391 |
+
"""Wrapper class around underlying C implementation."""
|
392 |
+
|
393 |
+
__slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
|
394 |
+
|
395 |
+
def __init__(self, pid):
|
396 |
+
self.pid = pid
|
397 |
+
self._name = None
|
398 |
+
self._ppid = None
|
399 |
+
self._procfs_path = get_procfs_path()
|
400 |
+
|
401 |
+
def _assert_alive(self):
|
402 |
+
"""Raise NSP if the process disappeared on us."""
|
403 |
+
# For those C function who do not raise NSP, possibly returning
|
404 |
+
# incorrect or incomplete result.
|
405 |
+
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
406 |
+
|
407 |
+
def oneshot_enter(self):
|
408 |
+
self._proc_name_and_args.cache_activate(self)
|
409 |
+
self._proc_basic_info.cache_activate(self)
|
410 |
+
self._proc_cred.cache_activate(self)
|
411 |
+
|
412 |
+
def oneshot_exit(self):
|
413 |
+
self._proc_name_and_args.cache_deactivate(self)
|
414 |
+
self._proc_basic_info.cache_deactivate(self)
|
415 |
+
self._proc_cred.cache_deactivate(self)
|
416 |
+
|
417 |
+
@wrap_exceptions
|
418 |
+
@memoize_when_activated
|
419 |
+
def _proc_name_and_args(self):
|
420 |
+
return cext.proc_name_and_args(self.pid, self._procfs_path)
|
421 |
+
|
422 |
+
@wrap_exceptions
|
423 |
+
@memoize_when_activated
|
424 |
+
def _proc_basic_info(self):
|
425 |
+
if self.pid == 0 and not os.path.exists(
|
426 |
+
'%s/%s/psinfo' % (self._procfs_path, self.pid)
|
427 |
+
):
|
428 |
+
raise AccessDenied(self.pid)
|
429 |
+
ret = cext.proc_basic_info(self.pid, self._procfs_path)
|
430 |
+
assert len(ret) == len(proc_info_map)
|
431 |
+
return ret
|
432 |
+
|
433 |
+
@wrap_exceptions
|
434 |
+
@memoize_when_activated
|
435 |
+
def _proc_cred(self):
|
436 |
+
return cext.proc_cred(self.pid, self._procfs_path)
|
437 |
+
|
438 |
+
@wrap_exceptions
|
439 |
+
def name(self):
|
440 |
+
# note: max len == 15
|
441 |
+
return self._proc_name_and_args()[0]
|
442 |
+
|
443 |
+
@wrap_exceptions
|
444 |
+
def exe(self):
|
445 |
+
try:
|
446 |
+
return os.readlink(
|
447 |
+
"%s/%s/path/a.out" % (self._procfs_path, self.pid)
|
448 |
+
)
|
449 |
+
except OSError:
|
450 |
+
pass # continue and guess the exe name from the cmdline
|
451 |
+
# Will be guessed later from cmdline but we want to explicitly
|
452 |
+
# invoke cmdline here in order to get an AccessDenied
|
453 |
+
# exception if the user has not enough privileges.
|
454 |
+
self.cmdline()
|
455 |
+
return ""
|
456 |
+
|
457 |
+
@wrap_exceptions
|
458 |
+
def cmdline(self):
|
459 |
+
return self._proc_name_and_args()[1].split(' ')
|
460 |
+
|
461 |
+
@wrap_exceptions
|
462 |
+
def environ(self):
|
463 |
+
return cext.proc_environ(self.pid, self._procfs_path)
|
464 |
+
|
465 |
+
@wrap_exceptions
|
466 |
+
def create_time(self):
|
467 |
+
return self._proc_basic_info()[proc_info_map['create_time']]
|
468 |
+
|
469 |
+
@wrap_exceptions
|
470 |
+
def num_threads(self):
|
471 |
+
return self._proc_basic_info()[proc_info_map['num_threads']]
|
472 |
+
|
473 |
+
@wrap_exceptions
|
474 |
+
def nice_get(self):
|
475 |
+
# Note #1: getpriority(3) doesn't work for realtime processes.
|
476 |
+
# Psinfo is what ps uses, see:
|
477 |
+
# https://github.com/giampaolo/psutil/issues/1194
|
478 |
+
return self._proc_basic_info()[proc_info_map['nice']]
|
479 |
+
|
480 |
+
@wrap_exceptions
|
481 |
+
def nice_set(self, value):
|
482 |
+
if self.pid in (2, 3):
|
483 |
+
# Special case PIDs: internally setpriority(3) return ESRCH
|
484 |
+
# (no such process), no matter what.
|
485 |
+
# The process actually exists though, as it has a name,
|
486 |
+
# creation time, etc.
|
487 |
+
raise AccessDenied(self.pid, self._name)
|
488 |
+
return cext_posix.setpriority(self.pid, value)
|
489 |
+
|
490 |
+
@wrap_exceptions
|
491 |
+
def ppid(self):
|
492 |
+
self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
|
493 |
+
return self._ppid
|
494 |
+
|
495 |
+
@wrap_exceptions
|
496 |
+
def uids(self):
|
497 |
+
try:
|
498 |
+
real, effective, saved, _, _, _ = self._proc_cred()
|
499 |
+
except AccessDenied:
|
500 |
+
real = self._proc_basic_info()[proc_info_map['uid']]
|
501 |
+
effective = self._proc_basic_info()[proc_info_map['euid']]
|
502 |
+
saved = None
|
503 |
+
return _common.puids(real, effective, saved)
|
504 |
+
|
505 |
+
@wrap_exceptions
|
506 |
+
def gids(self):
|
507 |
+
try:
|
508 |
+
_, _, _, real, effective, saved = self._proc_cred()
|
509 |
+
except AccessDenied:
|
510 |
+
real = self._proc_basic_info()[proc_info_map['gid']]
|
511 |
+
effective = self._proc_basic_info()[proc_info_map['egid']]
|
512 |
+
saved = None
|
513 |
+
return _common.puids(real, effective, saved)
|
514 |
+
|
515 |
+
@wrap_exceptions
|
516 |
+
def cpu_times(self):
|
517 |
+
try:
|
518 |
+
times = cext.proc_cpu_times(self.pid, self._procfs_path)
|
519 |
+
except OSError as err:
|
520 |
+
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
|
521 |
+
# We may get here if we attempt to query a 64bit process
|
522 |
+
# with a 32bit python.
|
523 |
+
# Error originates from read() and also tools like "cat"
|
524 |
+
# fail in the same way (!).
|
525 |
+
# Since there simply is no way to determine CPU times we
|
526 |
+
# return 0.0 as a fallback. See:
|
527 |
+
# https://github.com/giampaolo/psutil/issues/857
|
528 |
+
times = (0.0, 0.0, 0.0, 0.0)
|
529 |
+
else:
|
530 |
+
raise
|
531 |
+
return _common.pcputimes(*times)
|
532 |
+
|
533 |
+
@wrap_exceptions
|
534 |
+
def cpu_num(self):
|
535 |
+
return cext.proc_cpu_num(self.pid, self._procfs_path)
|
536 |
+
|
537 |
+
@wrap_exceptions
|
538 |
+
def terminal(self):
|
539 |
+
procfs_path = self._procfs_path
|
540 |
+
hit_enoent = False
|
541 |
+
tty = wrap_exceptions(self._proc_basic_info()[proc_info_map['ttynr']])
|
542 |
+
if tty != cext.PRNODEV:
|
543 |
+
for x in (0, 1, 2, 255):
|
544 |
+
try:
|
545 |
+
return os.readlink(
|
546 |
+
'%s/%d/path/%d' % (procfs_path, self.pid, x)
|
547 |
+
)
|
548 |
+
except FileNotFoundError:
|
549 |
+
hit_enoent = True
|
550 |
+
continue
|
551 |
+
if hit_enoent:
|
552 |
+
self._assert_alive()
|
553 |
+
|
554 |
+
@wrap_exceptions
|
555 |
+
def cwd(self):
|
556 |
+
# /proc/PID/path/cwd may not be resolved by readlink() even if
|
557 |
+
# it exists (ls shows it). If that's the case and the process
|
558 |
+
# is still alive return None (we can return None also on BSD).
|
559 |
+
# Reference: http://goo.gl/55XgO
|
560 |
+
procfs_path = self._procfs_path
|
561 |
+
try:
|
562 |
+
return os.readlink("%s/%s/path/cwd" % (procfs_path, self.pid))
|
563 |
+
except FileNotFoundError:
|
564 |
+
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
|
565 |
+
return ""
|
566 |
+
|
567 |
+
@wrap_exceptions
|
568 |
+
def memory_info(self):
|
569 |
+
ret = self._proc_basic_info()
|
570 |
+
rss = ret[proc_info_map['rss']] * 1024
|
571 |
+
vms = ret[proc_info_map['vms']] * 1024
|
572 |
+
return pmem(rss, vms)
|
573 |
+
|
574 |
+
memory_full_info = memory_info
|
575 |
+
|
576 |
+
@wrap_exceptions
|
577 |
+
def status(self):
|
578 |
+
code = self._proc_basic_info()[proc_info_map['status']]
|
579 |
+
# XXX is '?' legit? (we're not supposed to return it anyway)
|
580 |
+
return PROC_STATUSES.get(code, '?')
|
581 |
+
|
582 |
+
@wrap_exceptions
|
583 |
+
def threads(self):
|
584 |
+
procfs_path = self._procfs_path
|
585 |
+
ret = []
|
586 |
+
tids = os.listdir('%s/%d/lwp' % (procfs_path, self.pid))
|
587 |
+
hit_enoent = False
|
588 |
+
for tid in tids:
|
589 |
+
tid = int(tid)
|
590 |
+
try:
|
591 |
+
utime, stime = cext.query_process_thread(
|
592 |
+
self.pid, tid, procfs_path
|
593 |
+
)
|
594 |
+
except EnvironmentError as err:
|
595 |
+
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
|
596 |
+
# We may get here if we attempt to query a 64bit process
|
597 |
+
# with a 32bit python.
|
598 |
+
# Error originates from read() and also tools like "cat"
|
599 |
+
# fail in the same way (!).
|
600 |
+
# Since there simply is no way to determine CPU times we
|
601 |
+
# return 0.0 as a fallback. See:
|
602 |
+
# https://github.com/giampaolo/psutil/issues/857
|
603 |
+
continue
|
604 |
+
# ENOENT == thread gone in meantime
|
605 |
+
if err.errno == errno.ENOENT:
|
606 |
+
hit_enoent = True
|
607 |
+
continue
|
608 |
+
raise
|
609 |
+
else:
|
610 |
+
nt = _common.pthread(tid, utime, stime)
|
611 |
+
ret.append(nt)
|
612 |
+
if hit_enoent:
|
613 |
+
self._assert_alive()
|
614 |
+
return ret
|
615 |
+
|
616 |
+
@wrap_exceptions
|
617 |
+
def open_files(self):
|
618 |
+
retlist = []
|
619 |
+
hit_enoent = False
|
620 |
+
procfs_path = self._procfs_path
|
621 |
+
pathdir = '%s/%d/path' % (procfs_path, self.pid)
|
622 |
+
for fd in os.listdir('%s/%d/fd' % (procfs_path, self.pid)):
|
623 |
+
path = os.path.join(pathdir, fd)
|
624 |
+
if os.path.islink(path):
|
625 |
+
try:
|
626 |
+
file = os.readlink(path)
|
627 |
+
except FileNotFoundError:
|
628 |
+
hit_enoent = True
|
629 |
+
continue
|
630 |
+
else:
|
631 |
+
if isfile_strict(file):
|
632 |
+
retlist.append(_common.popenfile(file, int(fd)))
|
633 |
+
if hit_enoent:
|
634 |
+
self._assert_alive()
|
635 |
+
return retlist
|
636 |
+
|
637 |
+
def _get_unix_sockets(self, pid):
|
638 |
+
"""Get UNIX sockets used by process by parsing 'pfiles' output."""
|
639 |
+
# TODO: rewrite this in C (...but the damn netstat source code
|
640 |
+
# does not include this part! Argh!!)
|
641 |
+
cmd = ["pfiles", str(pid)]
|
642 |
+
p = subprocess.Popen(
|
643 |
+
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
644 |
+
)
|
645 |
+
stdout, stderr = p.communicate()
|
646 |
+
if PY3:
|
647 |
+
stdout, stderr = (
|
648 |
+
x.decode(sys.stdout.encoding) for x in (stdout, stderr)
|
649 |
+
)
|
650 |
+
if p.returncode != 0:
|
651 |
+
if 'permission denied' in stderr.lower():
|
652 |
+
raise AccessDenied(self.pid, self._name)
|
653 |
+
if 'no such process' in stderr.lower():
|
654 |
+
raise NoSuchProcess(self.pid, self._name)
|
655 |
+
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
|
656 |
+
|
657 |
+
lines = stdout.split('\n')[2:]
|
658 |
+
for i, line in enumerate(lines):
|
659 |
+
line = line.lstrip()
|
660 |
+
if line.startswith('sockname: AF_UNIX'):
|
661 |
+
path = line.split(' ', 2)[2]
|
662 |
+
type = lines[i - 2].strip()
|
663 |
+
if type == 'SOCK_STREAM':
|
664 |
+
type = socket.SOCK_STREAM
|
665 |
+
elif type == 'SOCK_DGRAM':
|
666 |
+
type = socket.SOCK_DGRAM
|
667 |
+
else:
|
668 |
+
type = -1
|
669 |
+
yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
|
670 |
+
|
671 |
+
@wrap_exceptions
|
672 |
+
def connections(self, kind='inet'):
|
673 |
+
ret = net_connections(kind, _pid=self.pid)
|
674 |
+
# The underlying C implementation retrieves all OS connections
|
675 |
+
# and filters them by PID. At this point we can't tell whether
|
676 |
+
# an empty list means there were no connections for process or
|
677 |
+
# process is no longer active so we force NSP in case the PID
|
678 |
+
# is no longer there.
|
679 |
+
if not ret:
|
680 |
+
# will raise NSP if process is gone
|
681 |
+
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
682 |
+
|
683 |
+
# UNIX sockets
|
684 |
+
if kind in ('all', 'unix'):
|
685 |
+
ret.extend([
|
686 |
+
_common.pconn(*conn)
|
687 |
+
for conn in self._get_unix_sockets(self.pid)
|
688 |
+
])
|
689 |
+
return ret
|
690 |
+
|
691 |
+
nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked')
|
692 |
+
nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked')
|
693 |
+
|
694 |
+
@wrap_exceptions
|
695 |
+
def memory_maps(self):
|
696 |
+
def toaddr(start, end):
|
697 |
+
return '%s-%s' % (
|
698 |
+
hex(start)[2:].strip('L'),
|
699 |
+
hex(end)[2:].strip('L'),
|
700 |
+
)
|
701 |
+
|
702 |
+
procfs_path = self._procfs_path
|
703 |
+
retlist = []
|
704 |
+
try:
|
705 |
+
rawlist = cext.proc_memory_maps(self.pid, procfs_path)
|
706 |
+
except OSError as err:
|
707 |
+
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
|
708 |
+
# We may get here if we attempt to query a 64bit process
|
709 |
+
# with a 32bit python.
|
710 |
+
# Error originates from read() and also tools like "cat"
|
711 |
+
# fail in the same way (!).
|
712 |
+
# Since there simply is no way to determine CPU times we
|
713 |
+
# return 0.0 as a fallback. See:
|
714 |
+
# https://github.com/giampaolo/psutil/issues/857
|
715 |
+
return []
|
716 |
+
else:
|
717 |
+
raise
|
718 |
+
hit_enoent = False
|
719 |
+
for item in rawlist:
|
720 |
+
addr, addrsize, perm, name, rss, anon, locked = item
|
721 |
+
addr = toaddr(addr, addrsize)
|
722 |
+
if not name.startswith('['):
|
723 |
+
try:
|
724 |
+
name = os.readlink(
|
725 |
+
'%s/%s/path/%s' % (procfs_path, self.pid, name)
|
726 |
+
)
|
727 |
+
except OSError as err:
|
728 |
+
if err.errno == errno.ENOENT:
|
729 |
+
# sometimes the link may not be resolved by
|
730 |
+
# readlink() even if it exists (ls shows it).
|
731 |
+
# If that's the case we just return the
|
732 |
+
# unresolved link path.
|
733 |
+
# This seems an incosistency with /proc similar
|
734 |
+
# to: http://goo.gl/55XgO
|
735 |
+
name = '%s/%s/path/%s' % (procfs_path, self.pid, name)
|
736 |
+
hit_enoent = True
|
737 |
+
else:
|
738 |
+
raise
|
739 |
+
retlist.append((addr, perm, name, rss, anon, locked))
|
740 |
+
if hit_enoent:
|
741 |
+
self._assert_alive()
|
742 |
+
return retlist
|
743 |
+
|
744 |
+
@wrap_exceptions
|
745 |
+
def num_fds(self):
|
746 |
+
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
|
747 |
+
|
748 |
+
@wrap_exceptions
|
749 |
+
def num_ctx_switches(self):
|
750 |
+
return _common.pctxsw(
|
751 |
+
*cext.proc_num_ctx_switches(self.pid, self._procfs_path)
|
752 |
+
)
|
753 |
+
|
754 |
+
@wrap_exceptions
|
755 |
+
def wait(self, timeout=None):
|
756 |
+
return _psposix.wait_pid(self.pid, timeout, self._name)
|
env-llmeval/lib/python3.10/site-packages/psutil/_psutil_linux.abi3.so
ADDED
Binary file (115 kB). View file
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""Windows platform implementation."""
|
6 |
+
|
7 |
+
import contextlib
|
8 |
+
import errno
|
9 |
+
import functools
|
10 |
+
import os
|
11 |
+
import signal
|
12 |
+
import sys
|
13 |
+
import time
|
14 |
+
from collections import namedtuple
|
15 |
+
|
16 |
+
from . import _common
|
17 |
+
from ._common import ENCODING
|
18 |
+
from ._common import ENCODING_ERRS
|
19 |
+
from ._common import AccessDenied
|
20 |
+
from ._common import NoSuchProcess
|
21 |
+
from ._common import TimeoutExpired
|
22 |
+
from ._common import conn_tmap
|
23 |
+
from ._common import conn_to_ntuple
|
24 |
+
from ._common import debug
|
25 |
+
from ._common import isfile_strict
|
26 |
+
from ._common import memoize
|
27 |
+
from ._common import memoize_when_activated
|
28 |
+
from ._common import parse_environ_block
|
29 |
+
from ._common import usage_percent
|
30 |
+
from ._compat import PY3
|
31 |
+
from ._compat import long
|
32 |
+
from ._compat import lru_cache
|
33 |
+
from ._compat import range
|
34 |
+
from ._compat import unicode
|
35 |
+
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
|
36 |
+
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS
|
37 |
+
from ._psutil_windows import HIGH_PRIORITY_CLASS
|
38 |
+
from ._psutil_windows import IDLE_PRIORITY_CLASS
|
39 |
+
from ._psutil_windows import NORMAL_PRIORITY_CLASS
|
40 |
+
from ._psutil_windows import REALTIME_PRIORITY_CLASS
|
41 |
+
|
42 |
+
|
43 |
+
try:
|
44 |
+
from . import _psutil_windows as cext
|
45 |
+
except ImportError as err:
|
46 |
+
if (
|
47 |
+
str(err).lower().startswith("dll load failed")
|
48 |
+
and sys.getwindowsversion()[0] < 6
|
49 |
+
):
|
50 |
+
# We may get here if:
|
51 |
+
# 1) we are on an old Windows version
|
52 |
+
# 2) psutil was installed via pip + wheel
|
53 |
+
# See: https://github.com/giampaolo/psutil/issues/811
|
54 |
+
msg = "this Windows version is too old (< Windows Vista); "
|
55 |
+
msg += "psutil 3.4.2 is the latest version which supports Windows "
|
56 |
+
msg += "2000, XP and 2003 server"
|
57 |
+
raise RuntimeError(msg)
|
58 |
+
else:
|
59 |
+
raise
|
60 |
+
|
61 |
+
if PY3:
|
62 |
+
import enum
|
63 |
+
else:
|
64 |
+
enum = None
|
65 |
+
|
66 |
+
# process priority constants, import from __init__.py:
|
67 |
+
# http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
|
68 |
+
# fmt: off
|
69 |
+
__extra__all__ = [
|
70 |
+
"win_service_iter", "win_service_get",
|
71 |
+
# Process priority
|
72 |
+
"ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
|
73 |
+
"HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", "NORMAL_PRIORITY_CLASS",
|
74 |
+
"REALTIME_PRIORITY_CLASS",
|
75 |
+
# IO priority
|
76 |
+
"IOPRIO_VERYLOW", "IOPRIO_LOW", "IOPRIO_NORMAL", "IOPRIO_HIGH",
|
77 |
+
# others
|
78 |
+
"CONN_DELETE_TCB", "AF_LINK",
|
79 |
+
]
|
80 |
+
# fmt: on
|
81 |
+
|
82 |
+
|
83 |
+
# =====================================================================
|
84 |
+
# --- globals
|
85 |
+
# =====================================================================
|
86 |
+
|
87 |
+
CONN_DELETE_TCB = "DELETE_TCB"
|
88 |
+
ERROR_PARTIAL_COPY = 299
|
89 |
+
PYPY = '__pypy__' in sys.builtin_module_names
|
90 |
+
|
91 |
+
if enum is None:
|
92 |
+
AF_LINK = -1
|
93 |
+
else:
|
94 |
+
AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1})
|
95 |
+
AF_LINK = AddressFamily.AF_LINK
|
96 |
+
|
97 |
+
TCP_STATUSES = {
|
98 |
+
cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED,
|
99 |
+
cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT,
|
100 |
+
cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV,
|
101 |
+
cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1,
|
102 |
+
cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2,
|
103 |
+
cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT,
|
104 |
+
cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE,
|
105 |
+
cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
106 |
+
cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK,
|
107 |
+
cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN,
|
108 |
+
cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING,
|
109 |
+
cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB,
|
110 |
+
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
111 |
+
}
|
112 |
+
|
113 |
+
if enum is not None:
|
114 |
+
|
115 |
+
class Priority(enum.IntEnum):
|
116 |
+
ABOVE_NORMAL_PRIORITY_CLASS = ABOVE_NORMAL_PRIORITY_CLASS
|
117 |
+
BELOW_NORMAL_PRIORITY_CLASS = BELOW_NORMAL_PRIORITY_CLASS
|
118 |
+
HIGH_PRIORITY_CLASS = HIGH_PRIORITY_CLASS
|
119 |
+
IDLE_PRIORITY_CLASS = IDLE_PRIORITY_CLASS
|
120 |
+
NORMAL_PRIORITY_CLASS = NORMAL_PRIORITY_CLASS
|
121 |
+
REALTIME_PRIORITY_CLASS = REALTIME_PRIORITY_CLASS
|
122 |
+
|
123 |
+
globals().update(Priority.__members__)
|
124 |
+
|
125 |
+
if enum is None:
|
126 |
+
IOPRIO_VERYLOW = 0
|
127 |
+
IOPRIO_LOW = 1
|
128 |
+
IOPRIO_NORMAL = 2
|
129 |
+
IOPRIO_HIGH = 3
|
130 |
+
else:
|
131 |
+
|
132 |
+
class IOPriority(enum.IntEnum):
|
133 |
+
IOPRIO_VERYLOW = 0
|
134 |
+
IOPRIO_LOW = 1
|
135 |
+
IOPRIO_NORMAL = 2
|
136 |
+
IOPRIO_HIGH = 3
|
137 |
+
|
138 |
+
globals().update(IOPriority.__members__)
|
139 |
+
|
140 |
+
pinfo_map = dict(
|
141 |
+
num_handles=0,
|
142 |
+
ctx_switches=1,
|
143 |
+
user_time=2,
|
144 |
+
kernel_time=3,
|
145 |
+
create_time=4,
|
146 |
+
num_threads=5,
|
147 |
+
io_rcount=6,
|
148 |
+
io_wcount=7,
|
149 |
+
io_rbytes=8,
|
150 |
+
io_wbytes=9,
|
151 |
+
io_count_others=10,
|
152 |
+
io_bytes_others=11,
|
153 |
+
num_page_faults=12,
|
154 |
+
peak_wset=13,
|
155 |
+
wset=14,
|
156 |
+
peak_paged_pool=15,
|
157 |
+
paged_pool=16,
|
158 |
+
peak_non_paged_pool=17,
|
159 |
+
non_paged_pool=18,
|
160 |
+
pagefile=19,
|
161 |
+
peak_pagefile=20,
|
162 |
+
mem_private=21,
|
163 |
+
)
|
164 |
+
|
165 |
+
|
166 |
+
# =====================================================================
|
167 |
+
# --- named tuples
|
168 |
+
# =====================================================================
|
169 |
+
|
170 |
+
|
171 |
+
# fmt: off
|
172 |
+
# psutil.cpu_times()
|
173 |
+
scputimes = namedtuple('scputimes',
|
174 |
+
['user', 'system', 'idle', 'interrupt', 'dpc'])
|
175 |
+
# psutil.virtual_memory()
|
176 |
+
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
|
177 |
+
# psutil.Process.memory_info()
|
178 |
+
pmem = namedtuple(
|
179 |
+
'pmem', ['rss', 'vms',
|
180 |
+
'num_page_faults', 'peak_wset', 'wset', 'peak_paged_pool',
|
181 |
+
'paged_pool', 'peak_nonpaged_pool', 'nonpaged_pool',
|
182 |
+
'pagefile', 'peak_pagefile', 'private'])
|
183 |
+
# psutil.Process.memory_full_info()
|
184 |
+
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
|
185 |
+
# psutil.Process.memory_maps(grouped=True)
|
186 |
+
pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss'])
|
187 |
+
# psutil.Process.memory_maps(grouped=False)
|
188 |
+
pmmap_ext = namedtuple(
|
189 |
+
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
|
190 |
+
# psutil.Process.io_counters()
|
191 |
+
pio = namedtuple('pio', ['read_count', 'write_count',
|
192 |
+
'read_bytes', 'write_bytes',
|
193 |
+
'other_count', 'other_bytes'])
|
194 |
+
# fmt: on
|
195 |
+
|
196 |
+
|
197 |
+
# =====================================================================
|
198 |
+
# --- utils
|
199 |
+
# =====================================================================
|
200 |
+
|
201 |
+
|
202 |
+
@lru_cache(maxsize=512)
|
203 |
+
def convert_dos_path(s):
|
204 |
+
r"""Convert paths using native DOS format like:
|
205 |
+
"\Device\HarddiskVolume1\Windows\systemew\file.txt"
|
206 |
+
into:
|
207 |
+
"C:\Windows\systemew\file.txt".
|
208 |
+
"""
|
209 |
+
rawdrive = '\\'.join(s.split('\\')[:3])
|
210 |
+
driveletter = cext.QueryDosDevice(rawdrive)
|
211 |
+
remainder = s[len(rawdrive) :]
|
212 |
+
return os.path.join(driveletter, remainder)
|
213 |
+
|
214 |
+
|
215 |
+
def py2_strencode(s):
|
216 |
+
"""Encode a unicode string to a byte string by using the default fs
|
217 |
+
encoding + "replace" error handler.
|
218 |
+
"""
|
219 |
+
if PY3:
|
220 |
+
return s
|
221 |
+
else:
|
222 |
+
if isinstance(s, str):
|
223 |
+
return s
|
224 |
+
else:
|
225 |
+
return s.encode(ENCODING, ENCODING_ERRS)
|
226 |
+
|
227 |
+
|
228 |
+
@memoize
|
229 |
+
def getpagesize():
|
230 |
+
return cext.getpagesize()
|
231 |
+
|
232 |
+
|
233 |
+
# =====================================================================
|
234 |
+
# --- memory
|
235 |
+
# =====================================================================
|
236 |
+
|
237 |
+
|
238 |
+
def virtual_memory():
|
239 |
+
"""System virtual memory as a namedtuple."""
|
240 |
+
mem = cext.virtual_mem()
|
241 |
+
totphys, availphys, totsys, availsys = mem
|
242 |
+
#
|
243 |
+
total = totphys
|
244 |
+
avail = availphys
|
245 |
+
free = availphys
|
246 |
+
used = total - avail
|
247 |
+
percent = usage_percent((total - avail), total, round_=1)
|
248 |
+
return svmem(total, avail, percent, used, free)
|
249 |
+
|
250 |
+
|
251 |
+
def swap_memory():
|
252 |
+
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
|
253 |
+
mem = cext.virtual_mem()
|
254 |
+
|
255 |
+
total_phys = mem[0]
|
256 |
+
total_system = mem[2]
|
257 |
+
|
258 |
+
# system memory (commit total/limit) is the sum of physical and swap
|
259 |
+
# thus physical memory values need to be subtracted to get swap values
|
260 |
+
total = total_system - total_phys
|
261 |
+
# commit total is incremented immediately (decrementing free_system)
|
262 |
+
# while the corresponding free physical value is not decremented until
|
263 |
+
# pages are accessed, so we can't use free system memory for swap.
|
264 |
+
# instead, we calculate page file usage based on performance counter
|
265 |
+
if total > 0:
|
266 |
+
percentswap = cext.swap_percent()
|
267 |
+
used = int(0.01 * percentswap * total)
|
268 |
+
else:
|
269 |
+
percentswap = 0.0
|
270 |
+
used = 0
|
271 |
+
|
272 |
+
free = total - used
|
273 |
+
percent = round(percentswap, 1)
|
274 |
+
return _common.sswap(total, used, free, percent, 0, 0)
|
275 |
+
|
276 |
+
|
277 |
+
# =====================================================================
|
278 |
+
# --- disk
|
279 |
+
# =====================================================================
|
280 |
+
|
281 |
+
|
282 |
+
disk_io_counters = cext.disk_io_counters
|
283 |
+
|
284 |
+
|
285 |
+
def disk_usage(path):
|
286 |
+
"""Return disk usage associated with path."""
|
287 |
+
if PY3 and isinstance(path, bytes):
|
288 |
+
# XXX: do we want to use "strict"? Probably yes, in order
|
289 |
+
# to fail immediately. After all we are accepting input here...
|
290 |
+
path = path.decode(ENCODING, errors="strict")
|
291 |
+
total, free = cext.disk_usage(path)
|
292 |
+
used = total - free
|
293 |
+
percent = usage_percent(used, total, round_=1)
|
294 |
+
return _common.sdiskusage(total, used, free, percent)
|
295 |
+
|
296 |
+
|
297 |
+
def disk_partitions(all):
|
298 |
+
"""Return disk partitions."""
|
299 |
+
rawlist = cext.disk_partitions(all)
|
300 |
+
return [_common.sdiskpart(*x) for x in rawlist]
|
301 |
+
|
302 |
+
|
303 |
+
# =====================================================================
|
304 |
+
# --- CPU
|
305 |
+
# =====================================================================
|
306 |
+
|
307 |
+
|
308 |
+
def cpu_times():
|
309 |
+
"""Return system CPU times as a named tuple."""
|
310 |
+
user, system, idle = cext.cpu_times()
|
311 |
+
# Internally, GetSystemTimes() is used, and it doesn't return
|
312 |
+
# interrupt and dpc times. cext.per_cpu_times() does, so we
|
313 |
+
# rely on it to get those only.
|
314 |
+
percpu_summed = scputimes(*[sum(n) for n in zip(*cext.per_cpu_times())])
|
315 |
+
return scputimes(
|
316 |
+
user, system, idle, percpu_summed.interrupt, percpu_summed.dpc
|
317 |
+
)
|
318 |
+
|
319 |
+
|
320 |
+
def per_cpu_times():
|
321 |
+
"""Return system per-CPU times as a list of named tuples."""
|
322 |
+
ret = []
|
323 |
+
for user, system, idle, interrupt, dpc in cext.per_cpu_times():
|
324 |
+
item = scputimes(user, system, idle, interrupt, dpc)
|
325 |
+
ret.append(item)
|
326 |
+
return ret
|
327 |
+
|
328 |
+
|
329 |
+
def cpu_count_logical():
|
330 |
+
"""Return the number of logical CPUs in the system."""
|
331 |
+
return cext.cpu_count_logical()
|
332 |
+
|
333 |
+
|
334 |
+
def cpu_count_cores():
|
335 |
+
"""Return the number of CPU cores in the system."""
|
336 |
+
return cext.cpu_count_cores()
|
337 |
+
|
338 |
+
|
339 |
+
def cpu_stats():
|
340 |
+
"""Return CPU statistics."""
|
341 |
+
ctx_switches, interrupts, dpcs, syscalls = cext.cpu_stats()
|
342 |
+
soft_interrupts = 0
|
343 |
+
return _common.scpustats(
|
344 |
+
ctx_switches, interrupts, soft_interrupts, syscalls
|
345 |
+
)
|
346 |
+
|
347 |
+
|
348 |
+
def cpu_freq():
|
349 |
+
"""Return CPU frequency.
|
350 |
+
On Windows per-cpu frequency is not supported.
|
351 |
+
"""
|
352 |
+
curr, max_ = cext.cpu_freq()
|
353 |
+
min_ = 0.0
|
354 |
+
return [_common.scpufreq(float(curr), min_, float(max_))]
|
355 |
+
|
356 |
+
|
357 |
+
_loadavg_inititialized = False
|
358 |
+
|
359 |
+
|
360 |
+
def getloadavg():
|
361 |
+
"""Return the number of processes in the system run queue averaged
|
362 |
+
over the last 1, 5, and 15 minutes respectively as a tuple.
|
363 |
+
"""
|
364 |
+
global _loadavg_inititialized
|
365 |
+
|
366 |
+
if not _loadavg_inititialized:
|
367 |
+
cext.init_loadavg_counter()
|
368 |
+
_loadavg_inititialized = True
|
369 |
+
|
370 |
+
# Drop to 2 decimal points which is what Linux does
|
371 |
+
raw_loads = cext.getloadavg()
|
372 |
+
return tuple([round(load, 2) for load in raw_loads])
|
373 |
+
|
374 |
+
|
375 |
+
# =====================================================================
|
376 |
+
# --- network
|
377 |
+
# =====================================================================
|
378 |
+
|
379 |
+
|
380 |
+
def net_connections(kind, _pid=-1):
|
381 |
+
"""Return socket connections. If pid == -1 return system-wide
|
382 |
+
connections (as opposed to connections opened by one process only).
|
383 |
+
"""
|
384 |
+
if kind not in conn_tmap:
|
385 |
+
raise ValueError(
|
386 |
+
"invalid %r kind argument; choose between %s"
|
387 |
+
% (kind, ', '.join([repr(x) for x in conn_tmap]))
|
388 |
+
)
|
389 |
+
families, types = conn_tmap[kind]
|
390 |
+
rawlist = cext.net_connections(_pid, families, types)
|
391 |
+
ret = set()
|
392 |
+
for item in rawlist:
|
393 |
+
fd, fam, type, laddr, raddr, status, pid = item
|
394 |
+
nt = conn_to_ntuple(
|
395 |
+
fd,
|
396 |
+
fam,
|
397 |
+
type,
|
398 |
+
laddr,
|
399 |
+
raddr,
|
400 |
+
status,
|
401 |
+
TCP_STATUSES,
|
402 |
+
pid=pid if _pid == -1 else None,
|
403 |
+
)
|
404 |
+
ret.add(nt)
|
405 |
+
return list(ret)
|
406 |
+
|
407 |
+
|
408 |
+
def net_if_stats():
|
409 |
+
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
410 |
+
ret = {}
|
411 |
+
rawdict = cext.net_if_stats()
|
412 |
+
for name, items in rawdict.items():
|
413 |
+
if not PY3:
|
414 |
+
assert isinstance(name, unicode), type(name)
|
415 |
+
name = py2_strencode(name)
|
416 |
+
isup, duplex, speed, mtu = items
|
417 |
+
if hasattr(_common, 'NicDuplex'):
|
418 |
+
duplex = _common.NicDuplex(duplex)
|
419 |
+
ret[name] = _common.snicstats(isup, duplex, speed, mtu, '')
|
420 |
+
return ret
|
421 |
+
|
422 |
+
|
423 |
+
def net_io_counters():
|
424 |
+
"""Return network I/O statistics for every network interface
|
425 |
+
installed on the system as a dict of raw tuples.
|
426 |
+
"""
|
427 |
+
ret = cext.net_io_counters()
|
428 |
+
return dict([(py2_strencode(k), v) for k, v in ret.items()])
|
429 |
+
|
430 |
+
|
431 |
+
def net_if_addrs():
|
432 |
+
"""Return the addresses associated to each NIC."""
|
433 |
+
ret = []
|
434 |
+
for items in cext.net_if_addrs():
|
435 |
+
items = list(items)
|
436 |
+
items[0] = py2_strencode(items[0])
|
437 |
+
ret.append(items)
|
438 |
+
return ret
|
439 |
+
|
440 |
+
|
441 |
+
# =====================================================================
|
442 |
+
# --- sensors
|
443 |
+
# =====================================================================
|
444 |
+
|
445 |
+
|
446 |
+
def sensors_battery():
|
447 |
+
"""Return battery information."""
|
448 |
+
# For constants meaning see:
|
449 |
+
# https://msdn.microsoft.com/en-us/library/windows/desktop/
|
450 |
+
# aa373232(v=vs.85).aspx
|
451 |
+
acline_status, flags, percent, secsleft = cext.sensors_battery()
|
452 |
+
power_plugged = acline_status == 1
|
453 |
+
no_battery = bool(flags & 128)
|
454 |
+
charging = bool(flags & 8)
|
455 |
+
|
456 |
+
if no_battery:
|
457 |
+
return None
|
458 |
+
if power_plugged or charging:
|
459 |
+
secsleft = _common.POWER_TIME_UNLIMITED
|
460 |
+
elif secsleft == -1:
|
461 |
+
secsleft = _common.POWER_TIME_UNKNOWN
|
462 |
+
|
463 |
+
return _common.sbattery(percent, secsleft, power_plugged)
|
464 |
+
|
465 |
+
|
466 |
+
# =====================================================================
|
467 |
+
# --- other system functions
|
468 |
+
# =====================================================================
|
469 |
+
|
470 |
+
|
471 |
+
_last_btime = 0
|
472 |
+
|
473 |
+
|
474 |
+
def boot_time():
|
475 |
+
"""The system boot time expressed in seconds since the epoch."""
|
476 |
+
# This dirty hack is to adjust the precision of the returned
|
477 |
+
# value which may have a 1 second fluctuation, see:
|
478 |
+
# https://github.com/giampaolo/psutil/issues/1007
|
479 |
+
global _last_btime
|
480 |
+
ret = float(cext.boot_time())
|
481 |
+
if abs(ret - _last_btime) <= 1:
|
482 |
+
return _last_btime
|
483 |
+
else:
|
484 |
+
_last_btime = ret
|
485 |
+
return ret
|
486 |
+
|
487 |
+
|
488 |
+
def users():
|
489 |
+
"""Return currently connected users as a list of namedtuples."""
|
490 |
+
retlist = []
|
491 |
+
rawlist = cext.users()
|
492 |
+
for item in rawlist:
|
493 |
+
user, hostname, tstamp = item
|
494 |
+
user = py2_strencode(user)
|
495 |
+
nt = _common.suser(user, None, hostname, tstamp, None)
|
496 |
+
retlist.append(nt)
|
497 |
+
return retlist
|
498 |
+
|
499 |
+
|
500 |
+
# =====================================================================
|
501 |
+
# --- Windows services
|
502 |
+
# =====================================================================
|
503 |
+
|
504 |
+
|
505 |
+
def win_service_iter():
|
506 |
+
"""Yields a list of WindowsService instances."""
|
507 |
+
for name, display_name in cext.winservice_enumerate():
|
508 |
+
yield WindowsService(py2_strencode(name), py2_strencode(display_name))
|
509 |
+
|
510 |
+
|
511 |
+
def win_service_get(name):
|
512 |
+
"""Open a Windows service and return it as a WindowsService instance."""
|
513 |
+
service = WindowsService(name, None)
|
514 |
+
service._display_name = service._query_config()['display_name']
|
515 |
+
return service
|
516 |
+
|
517 |
+
|
518 |
+
class WindowsService:
|
519 |
+
"""Represents an installed Windows service."""
|
520 |
+
|
521 |
+
def __init__(self, name, display_name):
|
522 |
+
self._name = name
|
523 |
+
self._display_name = display_name
|
524 |
+
|
525 |
+
def __str__(self):
|
526 |
+
details = "(name=%r, display_name=%r)" % (
|
527 |
+
self._name,
|
528 |
+
self._display_name,
|
529 |
+
)
|
530 |
+
return "%s%s" % (self.__class__.__name__, details)
|
531 |
+
|
532 |
+
def __repr__(self):
|
533 |
+
return "<%s at %s>" % (self.__str__(), id(self))
|
534 |
+
|
535 |
+
def __eq__(self, other):
|
536 |
+
# Test for equality with another WindosService object based
|
537 |
+
# on name.
|
538 |
+
if not isinstance(other, WindowsService):
|
539 |
+
return NotImplemented
|
540 |
+
return self._name == other._name
|
541 |
+
|
542 |
+
def __ne__(self, other):
|
543 |
+
return not self == other
|
544 |
+
|
545 |
+
def _query_config(self):
|
546 |
+
with self._wrap_exceptions():
|
547 |
+
display_name, binpath, username, start_type = (
|
548 |
+
cext.winservice_query_config(self._name)
|
549 |
+
)
|
550 |
+
# XXX - update _self.display_name?
|
551 |
+
return dict(
|
552 |
+
display_name=py2_strencode(display_name),
|
553 |
+
binpath=py2_strencode(binpath),
|
554 |
+
username=py2_strencode(username),
|
555 |
+
start_type=py2_strencode(start_type),
|
556 |
+
)
|
557 |
+
|
558 |
+
def _query_status(self):
|
559 |
+
with self._wrap_exceptions():
|
560 |
+
status, pid = cext.winservice_query_status(self._name)
|
561 |
+
if pid == 0:
|
562 |
+
pid = None
|
563 |
+
return dict(status=status, pid=pid)
|
564 |
+
|
565 |
+
@contextlib.contextmanager
|
566 |
+
def _wrap_exceptions(self):
|
567 |
+
"""Ctx manager which translates bare OSError and WindowsError
|
568 |
+
exceptions into NoSuchProcess and AccessDenied.
|
569 |
+
"""
|
570 |
+
try:
|
571 |
+
yield
|
572 |
+
except OSError as err:
|
573 |
+
if is_permission_err(err):
|
574 |
+
msg = (
|
575 |
+
"service %r is not querable (not enough privileges)"
|
576 |
+
% self._name
|
577 |
+
)
|
578 |
+
raise AccessDenied(pid=None, name=self._name, msg=msg)
|
579 |
+
elif err.winerror in (
|
580 |
+
cext.ERROR_INVALID_NAME,
|
581 |
+
cext.ERROR_SERVICE_DOES_NOT_EXIST,
|
582 |
+
):
|
583 |
+
msg = "service %r does not exist" % self._name
|
584 |
+
raise NoSuchProcess(pid=None, name=self._name, msg=msg)
|
585 |
+
else:
|
586 |
+
raise
|
587 |
+
|
588 |
+
# config query
|
589 |
+
|
590 |
+
def name(self):
|
591 |
+
"""The service name. This string is how a service is referenced
|
592 |
+
and can be passed to win_service_get() to get a new
|
593 |
+
WindowsService instance.
|
594 |
+
"""
|
595 |
+
return self._name
|
596 |
+
|
597 |
+
def display_name(self):
|
598 |
+
"""The service display name. The value is cached when this class
|
599 |
+
is instantiated.
|
600 |
+
"""
|
601 |
+
return self._display_name
|
602 |
+
|
603 |
+
def binpath(self):
|
604 |
+
"""The fully qualified path to the service binary/exe file as
|
605 |
+
a string, including command line arguments.
|
606 |
+
"""
|
607 |
+
return self._query_config()['binpath']
|
608 |
+
|
609 |
+
def username(self):
|
610 |
+
"""The name of the user that owns this service."""
|
611 |
+
return self._query_config()['username']
|
612 |
+
|
613 |
+
def start_type(self):
|
614 |
+
"""A string which can either be "automatic", "manual" or
|
615 |
+
"disabled".
|
616 |
+
"""
|
617 |
+
return self._query_config()['start_type']
|
618 |
+
|
619 |
+
# status query
|
620 |
+
|
621 |
+
def pid(self):
|
622 |
+
"""The process PID, if any, else None. This can be passed
|
623 |
+
to Process class to control the service's process.
|
624 |
+
"""
|
625 |
+
return self._query_status()['pid']
|
626 |
+
|
627 |
+
def status(self):
|
628 |
+
"""Service status as a string."""
|
629 |
+
return self._query_status()['status']
|
630 |
+
|
631 |
+
def description(self):
|
632 |
+
"""Service long description."""
|
633 |
+
return py2_strencode(cext.winservice_query_descr(self.name()))
|
634 |
+
|
635 |
+
# utils
|
636 |
+
|
637 |
+
def as_dict(self):
|
638 |
+
"""Utility method retrieving all the information above as a
|
639 |
+
dictionary.
|
640 |
+
"""
|
641 |
+
d = self._query_config()
|
642 |
+
d.update(self._query_status())
|
643 |
+
d['name'] = self.name()
|
644 |
+
d['display_name'] = self.display_name()
|
645 |
+
d['description'] = self.description()
|
646 |
+
return d
|
647 |
+
|
648 |
+
# actions
|
649 |
+
# XXX: the necessary C bindings for start() and stop() are
|
650 |
+
# implemented but for now I prefer not to expose them.
|
651 |
+
# I may change my mind in the future. Reasons:
|
652 |
+
# - they require Administrator privileges
|
653 |
+
# - can't implement a timeout for stop() (unless by using a thread,
|
654 |
+
# which sucks)
|
655 |
+
# - would require adding ServiceAlreadyStarted and
|
656 |
+
# ServiceAlreadyStopped exceptions, adding two new APIs.
|
657 |
+
# - we might also want to have modify(), which would basically mean
|
658 |
+
# rewriting win32serviceutil.ChangeServiceConfig, which involves a
|
659 |
+
# lot of stuff (and API constants which would pollute the API), see:
|
660 |
+
# http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/
|
661 |
+
# win32/lib/win32serviceutil.py.html#0175
|
662 |
+
# - psutil is typically about "read only" monitoring stuff;
|
663 |
+
# win_service_* APIs should only be used to retrieve a service and
|
664 |
+
# check whether it's running
|
665 |
+
|
666 |
+
# def start(self, timeout=None):
|
667 |
+
# with self._wrap_exceptions():
|
668 |
+
# cext.winservice_start(self.name())
|
669 |
+
# if timeout:
|
670 |
+
# giveup_at = time.time() + timeout
|
671 |
+
# while True:
|
672 |
+
# if self.status() == "running":
|
673 |
+
# return
|
674 |
+
# else:
|
675 |
+
# if time.time() > giveup_at:
|
676 |
+
# raise TimeoutExpired(timeout)
|
677 |
+
# else:
|
678 |
+
# time.sleep(.1)
|
679 |
+
|
680 |
+
# def stop(self):
|
681 |
+
# # Note: timeout is not implemented because it's just not
|
682 |
+
# # possible, see:
|
683 |
+
# # http://stackoverflow.com/questions/11973228/
|
684 |
+
# with self._wrap_exceptions():
|
685 |
+
# return cext.winservice_stop(self.name())
|
686 |
+
|
687 |
+
|
688 |
+
# =====================================================================
|
689 |
+
# --- processes
|
690 |
+
# =====================================================================
|
691 |
+
|
692 |
+
|
693 |
+
pids = cext.pids
|
694 |
+
pid_exists = cext.pid_exists
|
695 |
+
ppid_map = cext.ppid_map # used internally by Process.children()
|
696 |
+
|
697 |
+
|
698 |
+
def is_permission_err(exc):
|
699 |
+
"""Return True if this is a permission error."""
|
700 |
+
assert isinstance(exc, OSError), exc
|
701 |
+
if exc.errno in (errno.EPERM, errno.EACCES):
|
702 |
+
return True
|
703 |
+
# On Python 2 OSError doesn't always have 'winerror'. Sometimes
|
704 |
+
# it does, in which case the original exception was WindowsError
|
705 |
+
# (which is a subclass of OSError).
|
706 |
+
if getattr(exc, "winerror", -1) in (
|
707 |
+
cext.ERROR_ACCESS_DENIED,
|
708 |
+
cext.ERROR_PRIVILEGE_NOT_HELD,
|
709 |
+
):
|
710 |
+
return True
|
711 |
+
return False
|
712 |
+
|
713 |
+
|
714 |
+
def convert_oserror(exc, pid=None, name=None):
|
715 |
+
"""Convert OSError into NoSuchProcess or AccessDenied."""
|
716 |
+
assert isinstance(exc, OSError), exc
|
717 |
+
if is_permission_err(exc):
|
718 |
+
return AccessDenied(pid=pid, name=name)
|
719 |
+
if exc.errno == errno.ESRCH:
|
720 |
+
return NoSuchProcess(pid=pid, name=name)
|
721 |
+
raise exc
|
722 |
+
|
723 |
+
|
724 |
+
def wrap_exceptions(fun):
|
725 |
+
"""Decorator which converts OSError into NoSuchProcess or AccessDenied."""
|
726 |
+
|
727 |
+
@functools.wraps(fun)
|
728 |
+
def wrapper(self, *args, **kwargs):
|
729 |
+
try:
|
730 |
+
return fun(self, *args, **kwargs)
|
731 |
+
except OSError as err:
|
732 |
+
raise convert_oserror(err, pid=self.pid, name=self._name)
|
733 |
+
|
734 |
+
return wrapper
|
735 |
+
|
736 |
+
|
737 |
+
def retry_error_partial_copy(fun):
|
738 |
+
"""Workaround for https://github.com/giampaolo/psutil/issues/875.
|
739 |
+
See: https://stackoverflow.com/questions/4457745#4457745.
|
740 |
+
"""
|
741 |
+
|
742 |
+
@functools.wraps(fun)
|
743 |
+
def wrapper(self, *args, **kwargs):
|
744 |
+
delay = 0.0001
|
745 |
+
times = 33
|
746 |
+
for _ in range(times): # retries for roughly 1 second
|
747 |
+
try:
|
748 |
+
return fun(self, *args, **kwargs)
|
749 |
+
except WindowsError as _:
|
750 |
+
err = _
|
751 |
+
if err.winerror == ERROR_PARTIAL_COPY:
|
752 |
+
time.sleep(delay)
|
753 |
+
delay = min(delay * 2, 0.04)
|
754 |
+
continue
|
755 |
+
raise
|
756 |
+
msg = (
|
757 |
+
"{} retried {} times, converted to AccessDenied as it's still"
|
758 |
+
"returning {}".format(fun, times, err)
|
759 |
+
)
|
760 |
+
raise AccessDenied(pid=self.pid, name=self._name, msg=msg)
|
761 |
+
|
762 |
+
return wrapper
|
763 |
+
|
764 |
+
|
765 |
+
class Process:
|
766 |
+
"""Wrapper class around underlying C implementation."""
|
767 |
+
|
768 |
+
__slots__ = ["pid", "_name", "_ppid", "_cache"]
|
769 |
+
|
770 |
+
def __init__(self, pid):
|
771 |
+
self.pid = pid
|
772 |
+
self._name = None
|
773 |
+
self._ppid = None
|
774 |
+
|
775 |
+
# --- oneshot() stuff
|
776 |
+
|
777 |
+
def oneshot_enter(self):
|
778 |
+
self._proc_info.cache_activate(self)
|
779 |
+
self.exe.cache_activate(self)
|
780 |
+
|
781 |
+
def oneshot_exit(self):
|
782 |
+
self._proc_info.cache_deactivate(self)
|
783 |
+
self.exe.cache_deactivate(self)
|
784 |
+
|
785 |
+
@memoize_when_activated
|
786 |
+
def _proc_info(self):
|
787 |
+
"""Return multiple information about this process as a
|
788 |
+
raw tuple.
|
789 |
+
"""
|
790 |
+
ret = cext.proc_info(self.pid)
|
791 |
+
assert len(ret) == len(pinfo_map)
|
792 |
+
return ret
|
793 |
+
|
794 |
+
def name(self):
|
795 |
+
"""Return process name, which on Windows is always the final
|
796 |
+
part of the executable.
|
797 |
+
"""
|
798 |
+
# This is how PIDs 0 and 4 are always represented in taskmgr
|
799 |
+
# and process-hacker.
|
800 |
+
if self.pid == 0:
|
801 |
+
return "System Idle Process"
|
802 |
+
if self.pid == 4:
|
803 |
+
return "System"
|
804 |
+
return os.path.basename(self.exe())
|
805 |
+
|
806 |
+
@wrap_exceptions
|
807 |
+
@memoize_when_activated
|
808 |
+
def exe(self):
|
809 |
+
if PYPY:
|
810 |
+
try:
|
811 |
+
exe = cext.proc_exe(self.pid)
|
812 |
+
except WindowsError as err:
|
813 |
+
# 24 = ERROR_TOO_MANY_OPEN_FILES. Not sure why this happens
|
814 |
+
# (perhaps PyPy's JIT delaying garbage collection of files?).
|
815 |
+
if err.errno == 24:
|
816 |
+
debug("%r translated into AccessDenied" % err)
|
817 |
+
raise AccessDenied(self.pid, self._name)
|
818 |
+
raise
|
819 |
+
else:
|
820 |
+
exe = cext.proc_exe(self.pid)
|
821 |
+
if not PY3:
|
822 |
+
exe = py2_strencode(exe)
|
823 |
+
if exe.startswith('\\'):
|
824 |
+
return convert_dos_path(exe)
|
825 |
+
return exe # May be "Registry", "MemCompression", ...
|
826 |
+
|
827 |
+
@wrap_exceptions
|
828 |
+
@retry_error_partial_copy
|
829 |
+
def cmdline(self):
|
830 |
+
if cext.WINVER >= cext.WINDOWS_8_1:
|
831 |
+
# PEB method detects cmdline changes but requires more
|
832 |
+
# privileges: https://github.com/giampaolo/psutil/pull/1398
|
833 |
+
try:
|
834 |
+
ret = cext.proc_cmdline(self.pid, use_peb=True)
|
835 |
+
except OSError as err:
|
836 |
+
if is_permission_err(err):
|
837 |
+
ret = cext.proc_cmdline(self.pid, use_peb=False)
|
838 |
+
else:
|
839 |
+
raise
|
840 |
+
else:
|
841 |
+
ret = cext.proc_cmdline(self.pid, use_peb=True)
|
842 |
+
if PY3:
|
843 |
+
return ret
|
844 |
+
else:
|
845 |
+
return [py2_strencode(s) for s in ret]
|
846 |
+
|
847 |
+
@wrap_exceptions
|
848 |
+
@retry_error_partial_copy
|
849 |
+
def environ(self):
|
850 |
+
ustr = cext.proc_environ(self.pid)
|
851 |
+
if ustr and not PY3:
|
852 |
+
assert isinstance(ustr, unicode), type(ustr)
|
853 |
+
return parse_environ_block(py2_strencode(ustr))
|
854 |
+
|
855 |
+
def ppid(self):
|
856 |
+
try:
|
857 |
+
return ppid_map()[self.pid]
|
858 |
+
except KeyError:
|
859 |
+
raise NoSuchProcess(self.pid, self._name)
|
860 |
+
|
861 |
+
def _get_raw_meminfo(self):
|
862 |
+
try:
|
863 |
+
return cext.proc_memory_info(self.pid)
|
864 |
+
except OSError as err:
|
865 |
+
if is_permission_err(err):
|
866 |
+
# TODO: the C ext can probably be refactored in order
|
867 |
+
# to get this from cext.proc_info()
|
868 |
+
info = self._proc_info()
|
869 |
+
return (
|
870 |
+
info[pinfo_map['num_page_faults']],
|
871 |
+
info[pinfo_map['peak_wset']],
|
872 |
+
info[pinfo_map['wset']],
|
873 |
+
info[pinfo_map['peak_paged_pool']],
|
874 |
+
info[pinfo_map['paged_pool']],
|
875 |
+
info[pinfo_map['peak_non_paged_pool']],
|
876 |
+
info[pinfo_map['non_paged_pool']],
|
877 |
+
info[pinfo_map['pagefile']],
|
878 |
+
info[pinfo_map['peak_pagefile']],
|
879 |
+
info[pinfo_map['mem_private']],
|
880 |
+
)
|
881 |
+
raise
|
882 |
+
|
883 |
+
@wrap_exceptions
|
884 |
+
def memory_info(self):
|
885 |
+
# on Windows RSS == WorkingSetSize and VSM == PagefileUsage.
|
886 |
+
# Underlying C function returns fields of PROCESS_MEMORY_COUNTERS
|
887 |
+
# struct.
|
888 |
+
t = self._get_raw_meminfo()
|
889 |
+
rss = t[2] # wset
|
890 |
+
vms = t[7] # pagefile
|
891 |
+
return pmem(*(rss, vms) + t)
|
892 |
+
|
893 |
+
@wrap_exceptions
|
894 |
+
def memory_full_info(self):
|
895 |
+
basic_mem = self.memory_info()
|
896 |
+
uss = cext.proc_memory_uss(self.pid)
|
897 |
+
uss *= getpagesize()
|
898 |
+
return pfullmem(*basic_mem + (uss,))
|
899 |
+
|
900 |
+
def memory_maps(self):
|
901 |
+
try:
|
902 |
+
raw = cext.proc_memory_maps(self.pid)
|
903 |
+
except OSError as err:
|
904 |
+
# XXX - can't use wrap_exceptions decorator as we're
|
905 |
+
# returning a generator; probably needs refactoring.
|
906 |
+
raise convert_oserror(err, self.pid, self._name)
|
907 |
+
else:
|
908 |
+
for addr, perm, path, rss in raw:
|
909 |
+
path = convert_dos_path(path)
|
910 |
+
if not PY3:
|
911 |
+
path = py2_strencode(path)
|
912 |
+
addr = hex(addr)
|
913 |
+
yield (addr, perm, path, rss)
|
914 |
+
|
915 |
+
@wrap_exceptions
|
916 |
+
def kill(self):
|
917 |
+
return cext.proc_kill(self.pid)
|
918 |
+
|
919 |
+
@wrap_exceptions
|
920 |
+
def send_signal(self, sig):
|
921 |
+
if sig == signal.SIGTERM:
|
922 |
+
cext.proc_kill(self.pid)
|
923 |
+
# py >= 2.7
|
924 |
+
elif sig in (
|
925 |
+
getattr(signal, "CTRL_C_EVENT", object()),
|
926 |
+
getattr(signal, "CTRL_BREAK_EVENT", object()),
|
927 |
+
):
|
928 |
+
os.kill(self.pid, sig)
|
929 |
+
else:
|
930 |
+
msg = (
|
931 |
+
"only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals "
|
932 |
+
"are supported on Windows"
|
933 |
+
)
|
934 |
+
raise ValueError(msg)
|
935 |
+
|
936 |
+
@wrap_exceptions
|
937 |
+
def wait(self, timeout=None):
|
938 |
+
if timeout is None:
|
939 |
+
cext_timeout = cext.INFINITE
|
940 |
+
else:
|
941 |
+
# WaitForSingleObject() expects time in milliseconds.
|
942 |
+
cext_timeout = int(timeout * 1000)
|
943 |
+
|
944 |
+
timer = getattr(time, 'monotonic', time.time)
|
945 |
+
stop_at = timer() + timeout if timeout is not None else None
|
946 |
+
|
947 |
+
try:
|
948 |
+
# Exit code is supposed to come from GetExitCodeProcess().
|
949 |
+
# May also be None if OpenProcess() failed with
|
950 |
+
# ERROR_INVALID_PARAMETER, meaning PID is already gone.
|
951 |
+
exit_code = cext.proc_wait(self.pid, cext_timeout)
|
952 |
+
except cext.TimeoutExpired:
|
953 |
+
# WaitForSingleObject() returned WAIT_TIMEOUT. Just raise.
|
954 |
+
raise TimeoutExpired(timeout, self.pid, self._name)
|
955 |
+
except cext.TimeoutAbandoned:
|
956 |
+
# WaitForSingleObject() returned WAIT_ABANDONED, see:
|
957 |
+
# https://github.com/giampaolo/psutil/issues/1224
|
958 |
+
# We'll just rely on the internal polling and return None
|
959 |
+
# when the PID disappears. Subprocess module does the same
|
960 |
+
# (return None):
|
961 |
+
# https://github.com/python/cpython/blob/
|
962 |
+
# be50a7b627d0aa37e08fa8e2d5568891f19903ce/
|
963 |
+
# Lib/subprocess.py#L1193-L1194
|
964 |
+
exit_code = None
|
965 |
+
|
966 |
+
# At this point WaitForSingleObject() returned WAIT_OBJECT_0,
|
967 |
+
# meaning the process is gone. Stupidly there are cases where
|
968 |
+
# its PID may still stick around so we do a further internal
|
969 |
+
# polling.
|
970 |
+
delay = 0.0001
|
971 |
+
while True:
|
972 |
+
if not pid_exists(self.pid):
|
973 |
+
return exit_code
|
974 |
+
if stop_at and timer() >= stop_at:
|
975 |
+
raise TimeoutExpired(timeout, pid=self.pid, name=self._name)
|
976 |
+
time.sleep(delay)
|
977 |
+
delay = min(delay * 2, 0.04) # incremental delay
|
978 |
+
|
979 |
+
@wrap_exceptions
|
980 |
+
def username(self):
|
981 |
+
if self.pid in (0, 4):
|
982 |
+
return 'NT AUTHORITY\\SYSTEM'
|
983 |
+
domain, user = cext.proc_username(self.pid)
|
984 |
+
return py2_strencode(domain) + '\\' + py2_strencode(user)
|
985 |
+
|
986 |
+
@wrap_exceptions
|
987 |
+
def create_time(self):
|
988 |
+
# Note: proc_times() not put under oneshot() 'cause create_time()
|
989 |
+
# is already cached by the main Process class.
|
990 |
+
try:
|
991 |
+
user, system, created = cext.proc_times(self.pid)
|
992 |
+
return created
|
993 |
+
except OSError as err:
|
994 |
+
if is_permission_err(err):
|
995 |
+
return self._proc_info()[pinfo_map['create_time']]
|
996 |
+
raise
|
997 |
+
|
998 |
+
@wrap_exceptions
|
999 |
+
def num_threads(self):
|
1000 |
+
return self._proc_info()[pinfo_map['num_threads']]
|
1001 |
+
|
1002 |
+
@wrap_exceptions
|
1003 |
+
def threads(self):
|
1004 |
+
rawlist = cext.proc_threads(self.pid)
|
1005 |
+
retlist = []
|
1006 |
+
for thread_id, utime, stime in rawlist:
|
1007 |
+
ntuple = _common.pthread(thread_id, utime, stime)
|
1008 |
+
retlist.append(ntuple)
|
1009 |
+
return retlist
|
1010 |
+
|
1011 |
+
@wrap_exceptions
|
1012 |
+
def cpu_times(self):
|
1013 |
+
try:
|
1014 |
+
user, system, created = cext.proc_times(self.pid)
|
1015 |
+
except OSError as err:
|
1016 |
+
if not is_permission_err(err):
|
1017 |
+
raise
|
1018 |
+
info = self._proc_info()
|
1019 |
+
user = info[pinfo_map['user_time']]
|
1020 |
+
system = info[pinfo_map['kernel_time']]
|
1021 |
+
# Children user/system times are not retrievable (set to 0).
|
1022 |
+
return _common.pcputimes(user, system, 0.0, 0.0)
|
1023 |
+
|
1024 |
+
@wrap_exceptions
|
1025 |
+
def suspend(self):
|
1026 |
+
cext.proc_suspend_or_resume(self.pid, True)
|
1027 |
+
|
1028 |
+
@wrap_exceptions
|
1029 |
+
def resume(self):
|
1030 |
+
cext.proc_suspend_or_resume(self.pid, False)
|
1031 |
+
|
1032 |
+
@wrap_exceptions
|
1033 |
+
@retry_error_partial_copy
|
1034 |
+
def cwd(self):
|
1035 |
+
if self.pid in (0, 4):
|
1036 |
+
raise AccessDenied(self.pid, self._name)
|
1037 |
+
# return a normalized pathname since the native C function appends
|
1038 |
+
# "\\" at the and of the path
|
1039 |
+
path = cext.proc_cwd(self.pid)
|
1040 |
+
return py2_strencode(os.path.normpath(path))
|
1041 |
+
|
1042 |
+
@wrap_exceptions
|
1043 |
+
def open_files(self):
|
1044 |
+
if self.pid in (0, 4):
|
1045 |
+
return []
|
1046 |
+
ret = set()
|
1047 |
+
# Filenames come in in native format like:
|
1048 |
+
# "\Device\HarddiskVolume1\Windows\systemew\file.txt"
|
1049 |
+
# Convert the first part in the corresponding drive letter
|
1050 |
+
# (e.g. "C:\") by using Windows's QueryDosDevice()
|
1051 |
+
raw_file_names = cext.proc_open_files(self.pid)
|
1052 |
+
for _file in raw_file_names:
|
1053 |
+
_file = convert_dos_path(_file)
|
1054 |
+
if isfile_strict(_file):
|
1055 |
+
if not PY3:
|
1056 |
+
_file = py2_strencode(_file)
|
1057 |
+
ntuple = _common.popenfile(_file, -1)
|
1058 |
+
ret.add(ntuple)
|
1059 |
+
return list(ret)
|
1060 |
+
|
1061 |
+
@wrap_exceptions
|
1062 |
+
def connections(self, kind='inet'):
|
1063 |
+
return net_connections(kind, _pid=self.pid)
|
1064 |
+
|
1065 |
+
@wrap_exceptions
|
1066 |
+
def nice_get(self):
|
1067 |
+
value = cext.proc_priority_get(self.pid)
|
1068 |
+
if enum is not None:
|
1069 |
+
value = Priority(value)
|
1070 |
+
return value
|
1071 |
+
|
1072 |
+
@wrap_exceptions
|
1073 |
+
def nice_set(self, value):
|
1074 |
+
return cext.proc_priority_set(self.pid, value)
|
1075 |
+
|
1076 |
+
@wrap_exceptions
|
1077 |
+
def ionice_get(self):
|
1078 |
+
ret = cext.proc_io_priority_get(self.pid)
|
1079 |
+
if enum is not None:
|
1080 |
+
ret = IOPriority(ret)
|
1081 |
+
return ret
|
1082 |
+
|
1083 |
+
@wrap_exceptions
|
1084 |
+
def ionice_set(self, ioclass, value):
|
1085 |
+
if value:
|
1086 |
+
msg = "value argument not accepted on Windows"
|
1087 |
+
raise TypeError(msg)
|
1088 |
+
if ioclass not in (
|
1089 |
+
IOPRIO_VERYLOW,
|
1090 |
+
IOPRIO_LOW,
|
1091 |
+
IOPRIO_NORMAL,
|
1092 |
+
IOPRIO_HIGH,
|
1093 |
+
):
|
1094 |
+
raise ValueError("%s is not a valid priority" % ioclass)
|
1095 |
+
cext.proc_io_priority_set(self.pid, ioclass)
|
1096 |
+
|
1097 |
+
@wrap_exceptions
|
1098 |
+
def io_counters(self):
|
1099 |
+
try:
|
1100 |
+
ret = cext.proc_io_counters(self.pid)
|
1101 |
+
except OSError as err:
|
1102 |
+
if not is_permission_err(err):
|
1103 |
+
raise
|
1104 |
+
info = self._proc_info()
|
1105 |
+
ret = (
|
1106 |
+
info[pinfo_map['io_rcount']],
|
1107 |
+
info[pinfo_map['io_wcount']],
|
1108 |
+
info[pinfo_map['io_rbytes']],
|
1109 |
+
info[pinfo_map['io_wbytes']],
|
1110 |
+
info[pinfo_map['io_count_others']],
|
1111 |
+
info[pinfo_map['io_bytes_others']],
|
1112 |
+
)
|
1113 |
+
return pio(*ret)
|
1114 |
+
|
1115 |
+
@wrap_exceptions
|
1116 |
+
def status(self):
|
1117 |
+
suspended = cext.proc_is_suspended(self.pid)
|
1118 |
+
if suspended:
|
1119 |
+
return _common.STATUS_STOPPED
|
1120 |
+
else:
|
1121 |
+
return _common.STATUS_RUNNING
|
1122 |
+
|
1123 |
+
@wrap_exceptions
|
1124 |
+
def cpu_affinity_get(self):
|
1125 |
+
def from_bitmask(x):
|
1126 |
+
return [i for i in range(64) if (1 << i) & x]
|
1127 |
+
|
1128 |
+
bitmask = cext.proc_cpu_affinity_get(self.pid)
|
1129 |
+
return from_bitmask(bitmask)
|
1130 |
+
|
1131 |
+
@wrap_exceptions
|
1132 |
+
def cpu_affinity_set(self, value):
|
1133 |
+
def to_bitmask(ls):
|
1134 |
+
if not ls:
|
1135 |
+
raise ValueError("invalid argument %r" % ls)
|
1136 |
+
out = 0
|
1137 |
+
for b in ls:
|
1138 |
+
out |= 2**b
|
1139 |
+
return out
|
1140 |
+
|
1141 |
+
# SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
|
1142 |
+
# is returned for an invalid CPU but this seems not to be true,
|
1143 |
+
# therefore we check CPUs validy beforehand.
|
1144 |
+
allcpus = list(range(len(per_cpu_times())))
|
1145 |
+
for cpu in value:
|
1146 |
+
if cpu not in allcpus:
|
1147 |
+
if not isinstance(cpu, (int, long)):
|
1148 |
+
raise TypeError(
|
1149 |
+
"invalid CPU %r; an integer is required" % cpu
|
1150 |
+
)
|
1151 |
+
else:
|
1152 |
+
raise ValueError("invalid CPU %r" % cpu)
|
1153 |
+
|
1154 |
+
bitmask = to_bitmask(value)
|
1155 |
+
cext.proc_cpu_affinity_set(self.pid, bitmask)
|
1156 |
+
|
1157 |
+
@wrap_exceptions
|
1158 |
+
def num_handles(self):
|
1159 |
+
try:
|
1160 |
+
return cext.proc_num_handles(self.pid)
|
1161 |
+
except OSError as err:
|
1162 |
+
if is_permission_err(err):
|
1163 |
+
return self._proc_info()[pinfo_map['num_handles']]
|
1164 |
+
raise
|
1165 |
+
|
1166 |
+
@wrap_exceptions
|
1167 |
+
def num_ctx_switches(self):
|
1168 |
+
ctx_switches = self._proc_info()[pinfo_map['ctx_switches']]
|
1169 |
+
# only voluntary ctx switches are supported
|
1170 |
+
return _common.pctxsw(ctx_switches, 0)
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__init__.py
ADDED
@@ -0,0 +1,2043 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
|
3 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
4 |
+
# Use of this source code is governed by a BSD-style license that can be
|
5 |
+
# found in the LICENSE file.
|
6 |
+
|
7 |
+
"""Test utilities."""
|
8 |
+
|
9 |
+
from __future__ import print_function
|
10 |
+
|
11 |
+
import atexit
|
12 |
+
import contextlib
|
13 |
+
import ctypes
|
14 |
+
import errno
|
15 |
+
import functools
|
16 |
+
import gc
|
17 |
+
import inspect
|
18 |
+
import os
|
19 |
+
import platform
|
20 |
+
import random
|
21 |
+
import re
|
22 |
+
import select
|
23 |
+
import shlex
|
24 |
+
import shutil
|
25 |
+
import signal
|
26 |
+
import socket
|
27 |
+
import stat
|
28 |
+
import subprocess
|
29 |
+
import sys
|
30 |
+
import tempfile
|
31 |
+
import textwrap
|
32 |
+
import threading
|
33 |
+
import time
|
34 |
+
import unittest
|
35 |
+
import warnings
|
36 |
+
from socket import AF_INET
|
37 |
+
from socket import AF_INET6
|
38 |
+
from socket import SOCK_STREAM
|
39 |
+
|
40 |
+
import psutil
|
41 |
+
from psutil import AIX
|
42 |
+
from psutil import LINUX
|
43 |
+
from psutil import MACOS
|
44 |
+
from psutil import NETBSD
|
45 |
+
from psutil import OPENBSD
|
46 |
+
from psutil import POSIX
|
47 |
+
from psutil import SUNOS
|
48 |
+
from psutil import WINDOWS
|
49 |
+
from psutil._common import bytes2human
|
50 |
+
from psutil._common import debug
|
51 |
+
from psutil._common import memoize
|
52 |
+
from psutil._common import print_color
|
53 |
+
from psutil._common import supports_ipv6
|
54 |
+
from psutil._compat import PY3
|
55 |
+
from psutil._compat import FileExistsError
|
56 |
+
from psutil._compat import FileNotFoundError
|
57 |
+
from psutil._compat import range
|
58 |
+
from psutil._compat import super
|
59 |
+
from psutil._compat import u
|
60 |
+
from psutil._compat import unicode
|
61 |
+
from psutil._compat import which
|
62 |
+
|
63 |
+
|
64 |
+
try:
|
65 |
+
from unittest import mock # py3
|
66 |
+
except ImportError:
|
67 |
+
with warnings.catch_warnings():
|
68 |
+
warnings.simplefilter("ignore")
|
69 |
+
import mock # NOQA - requires "pip install mock"
|
70 |
+
|
71 |
+
if PY3:
|
72 |
+
import enum
|
73 |
+
else:
|
74 |
+
enum = None
|
75 |
+
|
76 |
+
if POSIX:
|
77 |
+
from psutil._psposix import wait_pid
|
78 |
+
|
79 |
+
|
80 |
+
# fmt: off
|
81 |
+
__all__ = [
|
82 |
+
# constants
|
83 |
+
'APPVEYOR', 'DEVNULL', 'GLOBAL_TIMEOUT', 'TOLERANCE_SYS_MEM', 'NO_RETRIES',
|
84 |
+
'PYPY', 'PYTHON_EXE', 'PYTHON_EXE_ENV', 'ROOT_DIR', 'SCRIPTS_DIR',
|
85 |
+
'TESTFN_PREFIX', 'UNICODE_SUFFIX', 'INVALID_UNICODE_SUFFIX',
|
86 |
+
'CI_TESTING', 'VALID_PROC_STATUSES', 'TOLERANCE_DISK_USAGE', 'IS_64BIT',
|
87 |
+
"HAS_CPU_AFFINITY", "HAS_CPU_FREQ", "HAS_ENVIRON", "HAS_PROC_IO_COUNTERS",
|
88 |
+
"HAS_IONICE", "HAS_MEMORY_MAPS", "HAS_PROC_CPU_NUM", "HAS_RLIMIT",
|
89 |
+
"HAS_SENSORS_BATTERY", "HAS_BATTERY", "HAS_SENSORS_FANS",
|
90 |
+
"HAS_SENSORS_TEMPERATURES", "MACOS_11PLUS",
|
91 |
+
"MACOS_12PLUS", "COVERAGE",
|
92 |
+
# subprocesses
|
93 |
+
'pyrun', 'terminate', 'reap_children', 'spawn_testproc', 'spawn_zombie',
|
94 |
+
'spawn_children_pair',
|
95 |
+
# threads
|
96 |
+
'ThreadTask',
|
97 |
+
# test utils
|
98 |
+
'unittest', 'skip_on_access_denied', 'skip_on_not_implemented',
|
99 |
+
'retry_on_failure', 'TestMemoryLeak', 'PsutilTestCase',
|
100 |
+
'process_namespace', 'system_namespace', 'print_sysinfo',
|
101 |
+
'is_win_secure_system_proc',
|
102 |
+
# fs utils
|
103 |
+
'chdir', 'safe_rmpath', 'create_py_exe', 'create_c_exe', 'get_testfn',
|
104 |
+
# os
|
105 |
+
'get_winver', 'kernel_version',
|
106 |
+
# sync primitives
|
107 |
+
'call_until', 'wait_for_pid', 'wait_for_file',
|
108 |
+
# network
|
109 |
+
'check_net_address', 'filter_proc_connections',
|
110 |
+
'get_free_port', 'bind_socket', 'bind_unix_socket', 'tcp_socketpair',
|
111 |
+
'unix_socketpair', 'create_sockets',
|
112 |
+
# compat
|
113 |
+
'reload_module', 'import_module_by_path',
|
114 |
+
# others
|
115 |
+
'warn', 'copyload_shared_lib', 'is_namedtuple',
|
116 |
+
]
|
117 |
+
# fmt: on
|
118 |
+
|
119 |
+
|
120 |
+
# ===================================================================
|
121 |
+
# --- constants
|
122 |
+
# ===================================================================
|
123 |
+
|
124 |
+
# --- platforms
|
125 |
+
|
126 |
+
PYPY = '__pypy__' in sys.builtin_module_names
|
127 |
+
# whether we're running this test suite on a Continuous Integration service
|
128 |
+
APPVEYOR = 'APPVEYOR' in os.environ
|
129 |
+
GITHUB_ACTIONS = 'GITHUB_ACTIONS' in os.environ or 'CIBUILDWHEEL' in os.environ
|
130 |
+
CI_TESTING = APPVEYOR or GITHUB_ACTIONS
|
131 |
+
COVERAGE = 'COVERAGE_RUN' in os.environ
|
132 |
+
# are we a 64 bit process?
|
133 |
+
IS_64BIT = sys.maxsize > 2**32
|
134 |
+
|
135 |
+
|
136 |
+
@memoize
|
137 |
+
def macos_version():
|
138 |
+
version_str = platform.mac_ver()[0]
|
139 |
+
version = tuple(map(int, version_str.split(".")[:2]))
|
140 |
+
if version == (10, 16):
|
141 |
+
# When built against an older macOS SDK, Python will report
|
142 |
+
# macOS 10.16 instead of the real version.
|
143 |
+
version_str = subprocess.check_output(
|
144 |
+
[
|
145 |
+
sys.executable,
|
146 |
+
"-sS",
|
147 |
+
"-c",
|
148 |
+
"import platform; print(platform.mac_ver()[0])",
|
149 |
+
],
|
150 |
+
env={"SYSTEM_VERSION_COMPAT": "0"},
|
151 |
+
universal_newlines=True,
|
152 |
+
)
|
153 |
+
version = tuple(map(int, version_str.split(".")[:2]))
|
154 |
+
return version
|
155 |
+
|
156 |
+
|
157 |
+
if MACOS:
|
158 |
+
MACOS_11PLUS = macos_version() > (10, 15)
|
159 |
+
MACOS_12PLUS = macos_version() >= (12, 0)
|
160 |
+
else:
|
161 |
+
MACOS_11PLUS = False
|
162 |
+
MACOS_12PLUS = False
|
163 |
+
|
164 |
+
|
165 |
+
# --- configurable defaults
|
166 |
+
|
167 |
+
# how many times retry_on_failure() decorator will retry
|
168 |
+
NO_RETRIES = 10
|
169 |
+
# bytes tolerance for system-wide related tests
|
170 |
+
TOLERANCE_SYS_MEM = 5 * 1024 * 1024 # 5MB
|
171 |
+
TOLERANCE_DISK_USAGE = 10 * 1024 * 1024 # 10MB
|
172 |
+
# the timeout used in functions which have to wait
|
173 |
+
GLOBAL_TIMEOUT = 5
|
174 |
+
# be more tolerant if we're on CI in order to avoid false positives
|
175 |
+
if CI_TESTING:
|
176 |
+
NO_RETRIES *= 3
|
177 |
+
GLOBAL_TIMEOUT *= 3
|
178 |
+
TOLERANCE_SYS_MEM *= 4
|
179 |
+
TOLERANCE_DISK_USAGE *= 3
|
180 |
+
|
181 |
+
# --- file names
|
182 |
+
|
183 |
+
# Disambiguate TESTFN for parallel testing.
|
184 |
+
if os.name == 'java':
|
185 |
+
# Jython disallows @ in module names
|
186 |
+
TESTFN_PREFIX = '$psutil-%s-' % os.getpid()
|
187 |
+
else:
|
188 |
+
TESTFN_PREFIX = '@psutil-%s-' % os.getpid()
|
189 |
+
UNICODE_SUFFIX = u("-ƒőő")
|
190 |
+
# An invalid unicode string.
|
191 |
+
if PY3:
|
192 |
+
INVALID_UNICODE_SUFFIX = b"f\xc0\x80".decode('utf8', 'surrogateescape')
|
193 |
+
else:
|
194 |
+
INVALID_UNICODE_SUFFIX = "f\xc0\x80"
|
195 |
+
ASCII_FS = sys.getfilesystemencoding().lower() in ('ascii', 'us-ascii')
|
196 |
+
|
197 |
+
# --- paths
|
198 |
+
|
199 |
+
ROOT_DIR = os.path.realpath(
|
200 |
+
os.path.join(os.path.dirname(__file__), '..', '..')
|
201 |
+
)
|
202 |
+
SCRIPTS_DIR = os.environ.get(
|
203 |
+
"PSUTIL_SCRIPTS_DIR", os.path.join(ROOT_DIR, 'scripts')
|
204 |
+
)
|
205 |
+
HERE = os.path.realpath(os.path.dirname(__file__))
|
206 |
+
|
207 |
+
# --- support
|
208 |
+
|
209 |
+
HAS_CONNECTIONS_UNIX = POSIX and not SUNOS
|
210 |
+
HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity")
|
211 |
+
HAS_CPU_FREQ = hasattr(psutil, "cpu_freq")
|
212 |
+
HAS_GETLOADAVG = hasattr(psutil, "getloadavg")
|
213 |
+
HAS_ENVIRON = hasattr(psutil.Process, "environ")
|
214 |
+
HAS_IONICE = hasattr(psutil.Process, "ionice")
|
215 |
+
HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps")
|
216 |
+
HAS_NET_IO_COUNTERS = hasattr(psutil, "net_io_counters")
|
217 |
+
HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num")
|
218 |
+
HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters")
|
219 |
+
HAS_RLIMIT = hasattr(psutil.Process, "rlimit")
|
220 |
+
HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
|
221 |
+
try:
|
222 |
+
HAS_BATTERY = HAS_SENSORS_BATTERY and bool(psutil.sensors_battery())
|
223 |
+
except Exception: # noqa: BLE001
|
224 |
+
HAS_BATTERY = False
|
225 |
+
HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
|
226 |
+
HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")
|
227 |
+
HAS_THREADS = hasattr(psutil.Process, "threads")
|
228 |
+
SKIP_SYSCONS = (MACOS or AIX) and os.getuid() != 0
|
229 |
+
|
230 |
+
# --- misc
|
231 |
+
|
232 |
+
|
233 |
+
def _get_py_exe():
|
234 |
+
def attempt(exe):
|
235 |
+
try:
|
236 |
+
subprocess.check_call(
|
237 |
+
[exe, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
238 |
+
)
|
239 |
+
except subprocess.CalledProcessError:
|
240 |
+
return None
|
241 |
+
else:
|
242 |
+
return exe
|
243 |
+
|
244 |
+
env = os.environ.copy()
|
245 |
+
|
246 |
+
# On Windows, starting with python 3.7, virtual environments use a
|
247 |
+
# venv launcher startup process. This does not play well when
|
248 |
+
# counting spawned processes, or when relying on the PID of the
|
249 |
+
# spawned process to do some checks, e.g. connections check per PID.
|
250 |
+
# Let's use the base python in this case.
|
251 |
+
base = getattr(sys, "_base_executable", None)
|
252 |
+
if WINDOWS and sys.version_info >= (3, 7) and base is not None:
|
253 |
+
# We need to set __PYVENV_LAUNCHER__ to sys.executable for the
|
254 |
+
# base python executable to know about the environment.
|
255 |
+
env["__PYVENV_LAUNCHER__"] = sys.executable
|
256 |
+
return base, env
|
257 |
+
elif GITHUB_ACTIONS:
|
258 |
+
return sys.executable, env
|
259 |
+
elif MACOS:
|
260 |
+
exe = (
|
261 |
+
attempt(sys.executable)
|
262 |
+
or attempt(os.path.realpath(sys.executable))
|
263 |
+
or attempt(which("python%s.%s" % sys.version_info[:2]))
|
264 |
+
or attempt(psutil.Process().exe())
|
265 |
+
)
|
266 |
+
if not exe:
|
267 |
+
raise ValueError("can't find python exe real abspath")
|
268 |
+
return exe, env
|
269 |
+
else:
|
270 |
+
exe = os.path.realpath(sys.executable)
|
271 |
+
assert os.path.exists(exe), exe
|
272 |
+
return exe, env
|
273 |
+
|
274 |
+
|
275 |
+
PYTHON_EXE, PYTHON_EXE_ENV = _get_py_exe()
|
276 |
+
DEVNULL = open(os.devnull, 'r+')
|
277 |
+
atexit.register(DEVNULL.close)
|
278 |
+
|
279 |
+
VALID_PROC_STATUSES = [
|
280 |
+
getattr(psutil, x) for x in dir(psutil) if x.startswith('STATUS_')
|
281 |
+
]
|
282 |
+
AF_UNIX = getattr(socket, "AF_UNIX", object())
|
283 |
+
|
284 |
+
_subprocesses_started = set()
|
285 |
+
_pids_started = set()
|
286 |
+
|
287 |
+
|
288 |
+
# ===================================================================
|
289 |
+
# --- threads
|
290 |
+
# ===================================================================
|
291 |
+
|
292 |
+
|
293 |
+
class ThreadTask(threading.Thread):
|
294 |
+
"""A thread task which does nothing expect staying alive."""
|
295 |
+
|
296 |
+
def __init__(self):
|
297 |
+
super().__init__()
|
298 |
+
self._running = False
|
299 |
+
self._interval = 0.001
|
300 |
+
self._flag = threading.Event()
|
301 |
+
|
302 |
+
def __repr__(self):
|
303 |
+
name = self.__class__.__name__
|
304 |
+
return '<%s running=%s at %#x>' % (name, self._running, id(self))
|
305 |
+
|
306 |
+
def __enter__(self):
|
307 |
+
self.start()
|
308 |
+
return self
|
309 |
+
|
310 |
+
def __exit__(self, *args, **kwargs):
|
311 |
+
self.stop()
|
312 |
+
|
313 |
+
def start(self):
|
314 |
+
"""Start thread and keep it running until an explicit
|
315 |
+
stop() request. Polls for shutdown every 'timeout' seconds.
|
316 |
+
"""
|
317 |
+
if self._running:
|
318 |
+
raise ValueError("already started")
|
319 |
+
threading.Thread.start(self)
|
320 |
+
self._flag.wait()
|
321 |
+
|
322 |
+
def run(self):
|
323 |
+
self._running = True
|
324 |
+
self._flag.set()
|
325 |
+
while self._running:
|
326 |
+
time.sleep(self._interval)
|
327 |
+
|
328 |
+
def stop(self):
|
329 |
+
"""Stop thread execution and and waits until it is stopped."""
|
330 |
+
if not self._running:
|
331 |
+
raise ValueError("already stopped")
|
332 |
+
self._running = False
|
333 |
+
self.join()
|
334 |
+
|
335 |
+
|
336 |
+
# ===================================================================
|
337 |
+
# --- subprocesses
|
338 |
+
# ===================================================================
|
339 |
+
|
340 |
+
|
341 |
+
def _reap_children_on_err(fun):
|
342 |
+
@functools.wraps(fun)
|
343 |
+
def wrapper(*args, **kwargs):
|
344 |
+
try:
|
345 |
+
return fun(*args, **kwargs)
|
346 |
+
except Exception:
|
347 |
+
reap_children()
|
348 |
+
raise
|
349 |
+
|
350 |
+
return wrapper
|
351 |
+
|
352 |
+
|
353 |
+
@_reap_children_on_err
|
354 |
+
def spawn_testproc(cmd=None, **kwds):
|
355 |
+
"""Create a python subprocess which does nothing for some secs and
|
356 |
+
return it as a subprocess.Popen instance.
|
357 |
+
If "cmd" is specified that is used instead of python.
|
358 |
+
By default stdin and stdout are redirected to /dev/null.
|
359 |
+
It also attempts to make sure the process is in a reasonably
|
360 |
+
initialized state.
|
361 |
+
The process is registered for cleanup on reap_children().
|
362 |
+
"""
|
363 |
+
kwds.setdefault("stdin", DEVNULL)
|
364 |
+
kwds.setdefault("stdout", DEVNULL)
|
365 |
+
kwds.setdefault("cwd", os.getcwd())
|
366 |
+
kwds.setdefault("env", PYTHON_EXE_ENV)
|
367 |
+
if WINDOWS:
|
368 |
+
# Prevents the subprocess to open error dialogs. This will also
|
369 |
+
# cause stderr to be suppressed, which is suboptimal in order
|
370 |
+
# to debug broken tests.
|
371 |
+
CREATE_NO_WINDOW = 0x8000000
|
372 |
+
kwds.setdefault("creationflags", CREATE_NO_WINDOW)
|
373 |
+
if cmd is None:
|
374 |
+
testfn = get_testfn(dir=os.getcwd())
|
375 |
+
try:
|
376 |
+
safe_rmpath(testfn)
|
377 |
+
pyline = (
|
378 |
+
"import time;"
|
379 |
+
+ "open(r'%s', 'w').close();" % testfn
|
380 |
+
+ "[time.sleep(0.1) for x in range(100)];" # 10 secs
|
381 |
+
)
|
382 |
+
cmd = [PYTHON_EXE, "-c", pyline]
|
383 |
+
sproc = subprocess.Popen(cmd, **kwds)
|
384 |
+
_subprocesses_started.add(sproc)
|
385 |
+
wait_for_file(testfn, delete=True, empty=True)
|
386 |
+
finally:
|
387 |
+
safe_rmpath(testfn)
|
388 |
+
else:
|
389 |
+
sproc = subprocess.Popen(cmd, **kwds)
|
390 |
+
_subprocesses_started.add(sproc)
|
391 |
+
wait_for_pid(sproc.pid)
|
392 |
+
return sproc
|
393 |
+
|
394 |
+
|
395 |
+
@_reap_children_on_err
|
396 |
+
def spawn_children_pair():
|
397 |
+
"""Create a subprocess which creates another one as in:
|
398 |
+
A (us) -> B (child) -> C (grandchild).
|
399 |
+
Return a (child, grandchild) tuple.
|
400 |
+
The 2 processes are fully initialized and will live for 60 secs
|
401 |
+
and are registered for cleanup on reap_children().
|
402 |
+
"""
|
403 |
+
tfile = None
|
404 |
+
testfn = get_testfn(dir=os.getcwd())
|
405 |
+
try:
|
406 |
+
s = textwrap.dedent("""\
|
407 |
+
import subprocess, os, sys, time
|
408 |
+
s = "import os, time;"
|
409 |
+
s += "f = open('%s', 'w');"
|
410 |
+
s += "f.write(str(os.getpid()));"
|
411 |
+
s += "f.close();"
|
412 |
+
s += "time.sleep(60);"
|
413 |
+
p = subprocess.Popen([r'%s', '-c', s])
|
414 |
+
p.wait()
|
415 |
+
""" % (os.path.basename(testfn), PYTHON_EXE))
|
416 |
+
# On Windows if we create a subprocess with CREATE_NO_WINDOW flag
|
417 |
+
# set (which is the default) a "conhost.exe" extra process will be
|
418 |
+
# spawned as a child. We don't want that.
|
419 |
+
if WINDOWS:
|
420 |
+
subp, tfile = pyrun(s, creationflags=0)
|
421 |
+
else:
|
422 |
+
subp, tfile = pyrun(s)
|
423 |
+
child = psutil.Process(subp.pid)
|
424 |
+
grandchild_pid = int(wait_for_file(testfn, delete=True, empty=False))
|
425 |
+
_pids_started.add(grandchild_pid)
|
426 |
+
grandchild = psutil.Process(grandchild_pid)
|
427 |
+
return (child, grandchild)
|
428 |
+
finally:
|
429 |
+
safe_rmpath(testfn)
|
430 |
+
if tfile is not None:
|
431 |
+
safe_rmpath(tfile)
|
432 |
+
|
433 |
+
|
434 |
+
def spawn_zombie():
|
435 |
+
"""Create a zombie process and return a (parent, zombie) process tuple.
|
436 |
+
In order to kill the zombie parent must be terminate()d first, then
|
437 |
+
zombie must be wait()ed on.
|
438 |
+
"""
|
439 |
+
assert psutil.POSIX
|
440 |
+
unix_file = get_testfn()
|
441 |
+
src = textwrap.dedent("""\
|
442 |
+
import os, sys, time, socket, contextlib
|
443 |
+
child_pid = os.fork()
|
444 |
+
if child_pid > 0:
|
445 |
+
time.sleep(3000)
|
446 |
+
else:
|
447 |
+
# this is the zombie process
|
448 |
+
s = socket.socket(socket.AF_UNIX)
|
449 |
+
with contextlib.closing(s):
|
450 |
+
s.connect('%s')
|
451 |
+
if sys.version_info < (3, ):
|
452 |
+
pid = str(os.getpid())
|
453 |
+
else:
|
454 |
+
pid = bytes(str(os.getpid()), 'ascii')
|
455 |
+
s.sendall(pid)
|
456 |
+
""" % unix_file)
|
457 |
+
tfile = None
|
458 |
+
sock = bind_unix_socket(unix_file)
|
459 |
+
try:
|
460 |
+
sock.settimeout(GLOBAL_TIMEOUT)
|
461 |
+
parent, tfile = pyrun(src)
|
462 |
+
conn, _ = sock.accept()
|
463 |
+
try:
|
464 |
+
select.select([conn.fileno()], [], [], GLOBAL_TIMEOUT)
|
465 |
+
zpid = int(conn.recv(1024))
|
466 |
+
_pids_started.add(zpid)
|
467 |
+
zombie = psutil.Process(zpid)
|
468 |
+
call_until(zombie.status, "ret == psutil.STATUS_ZOMBIE")
|
469 |
+
return (parent, zombie)
|
470 |
+
finally:
|
471 |
+
conn.close()
|
472 |
+
finally:
|
473 |
+
sock.close()
|
474 |
+
safe_rmpath(unix_file)
|
475 |
+
if tfile is not None:
|
476 |
+
safe_rmpath(tfile)
|
477 |
+
|
478 |
+
|
479 |
+
@_reap_children_on_err
|
480 |
+
def pyrun(src, **kwds):
|
481 |
+
"""Run python 'src' code string in a separate interpreter.
|
482 |
+
Returns a subprocess.Popen instance and the test file where the source
|
483 |
+
code was written.
|
484 |
+
"""
|
485 |
+
kwds.setdefault("stdout", None)
|
486 |
+
kwds.setdefault("stderr", None)
|
487 |
+
srcfile = get_testfn()
|
488 |
+
try:
|
489 |
+
with open(srcfile, "w") as f:
|
490 |
+
f.write(src)
|
491 |
+
subp = spawn_testproc([PYTHON_EXE, f.name], **kwds)
|
492 |
+
wait_for_pid(subp.pid)
|
493 |
+
return (subp, srcfile)
|
494 |
+
except Exception:
|
495 |
+
safe_rmpath(srcfile)
|
496 |
+
raise
|
497 |
+
|
498 |
+
|
499 |
+
@_reap_children_on_err
|
500 |
+
def sh(cmd, **kwds):
|
501 |
+
"""Run cmd in a subprocess and return its output.
|
502 |
+
raises RuntimeError on error.
|
503 |
+
"""
|
504 |
+
# Prevents subprocess to open error dialogs in case of error.
|
505 |
+
flags = 0x8000000 if WINDOWS else 0
|
506 |
+
kwds.setdefault("stdout", subprocess.PIPE)
|
507 |
+
kwds.setdefault("stderr", subprocess.PIPE)
|
508 |
+
kwds.setdefault("universal_newlines", True)
|
509 |
+
kwds.setdefault("creationflags", flags)
|
510 |
+
if isinstance(cmd, str):
|
511 |
+
cmd = shlex.split(cmd)
|
512 |
+
p = subprocess.Popen(cmd, **kwds)
|
513 |
+
_subprocesses_started.add(p)
|
514 |
+
if PY3:
|
515 |
+
stdout, stderr = p.communicate(timeout=GLOBAL_TIMEOUT)
|
516 |
+
else:
|
517 |
+
stdout, stderr = p.communicate()
|
518 |
+
if p.returncode != 0:
|
519 |
+
raise RuntimeError(stderr)
|
520 |
+
if stderr:
|
521 |
+
warn(stderr)
|
522 |
+
if stdout.endswith('\n'):
|
523 |
+
stdout = stdout[:-1]
|
524 |
+
return stdout
|
525 |
+
|
526 |
+
|
527 |
+
def terminate(proc_or_pid, sig=signal.SIGTERM, wait_timeout=GLOBAL_TIMEOUT):
|
528 |
+
"""Terminate a process and wait() for it.
|
529 |
+
Process can be a PID or an instance of psutil.Process(),
|
530 |
+
subprocess.Popen() or psutil.Popen().
|
531 |
+
If it's a subprocess.Popen() or psutil.Popen() instance also closes
|
532 |
+
its stdin / stdout / stderr fds.
|
533 |
+
PID is wait()ed even if the process is already gone (kills zombies).
|
534 |
+
Does nothing if the process does not exist.
|
535 |
+
Return process exit status.
|
536 |
+
"""
|
537 |
+
|
538 |
+
def wait(proc, timeout):
|
539 |
+
if isinstance(proc, subprocess.Popen) and not PY3:
|
540 |
+
proc.wait()
|
541 |
+
else:
|
542 |
+
proc.wait(timeout)
|
543 |
+
if WINDOWS and isinstance(proc, subprocess.Popen):
|
544 |
+
# Otherwise PID may still hang around.
|
545 |
+
try:
|
546 |
+
return psutil.Process(proc.pid).wait(timeout)
|
547 |
+
except psutil.NoSuchProcess:
|
548 |
+
pass
|
549 |
+
|
550 |
+
def sendsig(proc, sig):
|
551 |
+
# XXX: otherwise the build hangs for some reason.
|
552 |
+
if MACOS and GITHUB_ACTIONS:
|
553 |
+
sig = signal.SIGKILL
|
554 |
+
# If the process received SIGSTOP, SIGCONT is necessary first,
|
555 |
+
# otherwise SIGTERM won't work.
|
556 |
+
if POSIX and sig != signal.SIGKILL:
|
557 |
+
proc.send_signal(signal.SIGCONT)
|
558 |
+
proc.send_signal(sig)
|
559 |
+
|
560 |
+
def term_subprocess_proc(proc, timeout):
|
561 |
+
try:
|
562 |
+
sendsig(proc, sig)
|
563 |
+
except OSError as err:
|
564 |
+
if WINDOWS and err.winerror == 6: # "invalid handle"
|
565 |
+
pass
|
566 |
+
elif err.errno != errno.ESRCH:
|
567 |
+
raise
|
568 |
+
return wait(proc, timeout)
|
569 |
+
|
570 |
+
def term_psutil_proc(proc, timeout):
|
571 |
+
try:
|
572 |
+
sendsig(proc, sig)
|
573 |
+
except psutil.NoSuchProcess:
|
574 |
+
pass
|
575 |
+
return wait(proc, timeout)
|
576 |
+
|
577 |
+
def term_pid(pid, timeout):
|
578 |
+
try:
|
579 |
+
proc = psutil.Process(pid)
|
580 |
+
except psutil.NoSuchProcess:
|
581 |
+
# Needed to kill zombies.
|
582 |
+
if POSIX:
|
583 |
+
return wait_pid(pid, timeout)
|
584 |
+
else:
|
585 |
+
return term_psutil_proc(proc, timeout)
|
586 |
+
|
587 |
+
def flush_popen(proc):
|
588 |
+
if proc.stdout:
|
589 |
+
proc.stdout.close()
|
590 |
+
if proc.stderr:
|
591 |
+
proc.stderr.close()
|
592 |
+
# Flushing a BufferedWriter may raise an error.
|
593 |
+
if proc.stdin:
|
594 |
+
proc.stdin.close()
|
595 |
+
|
596 |
+
p = proc_or_pid
|
597 |
+
try:
|
598 |
+
if isinstance(p, int):
|
599 |
+
return term_pid(p, wait_timeout)
|
600 |
+
elif isinstance(p, (psutil.Process, psutil.Popen)):
|
601 |
+
return term_psutil_proc(p, wait_timeout)
|
602 |
+
elif isinstance(p, subprocess.Popen):
|
603 |
+
return term_subprocess_proc(p, wait_timeout)
|
604 |
+
else:
|
605 |
+
raise TypeError("wrong type %r" % p)
|
606 |
+
finally:
|
607 |
+
if isinstance(p, (subprocess.Popen, psutil.Popen)):
|
608 |
+
flush_popen(p)
|
609 |
+
pid = p if isinstance(p, int) else p.pid
|
610 |
+
assert not psutil.pid_exists(pid), pid
|
611 |
+
|
612 |
+
|
613 |
+
def reap_children(recursive=False):
|
614 |
+
"""Terminate and wait() any subprocess started by this test suite
|
615 |
+
and any children currently running, ensuring that no processes stick
|
616 |
+
around to hog resources.
|
617 |
+
If recursive is True it also tries to terminate and wait()
|
618 |
+
all grandchildren started by this process.
|
619 |
+
"""
|
620 |
+
# Get the children here before terminating them, as in case of
|
621 |
+
# recursive=True we don't want to lose the intermediate reference
|
622 |
+
# pointing to the grandchildren.
|
623 |
+
children = psutil.Process().children(recursive=recursive)
|
624 |
+
|
625 |
+
# Terminate subprocess.Popen.
|
626 |
+
while _subprocesses_started:
|
627 |
+
subp = _subprocesses_started.pop()
|
628 |
+
terminate(subp)
|
629 |
+
|
630 |
+
# Collect started pids.
|
631 |
+
while _pids_started:
|
632 |
+
pid = _pids_started.pop()
|
633 |
+
terminate(pid)
|
634 |
+
|
635 |
+
# Terminate children.
|
636 |
+
if children:
|
637 |
+
for p in children:
|
638 |
+
terminate(p, wait_timeout=None)
|
639 |
+
_, alive = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT)
|
640 |
+
for p in alive:
|
641 |
+
warn("couldn't terminate process %r; attempting kill()" % p)
|
642 |
+
terminate(p, sig=signal.SIGKILL)
|
643 |
+
|
644 |
+
|
645 |
+
# ===================================================================
|
646 |
+
# --- OS
|
647 |
+
# ===================================================================
|
648 |
+
|
649 |
+
|
650 |
+
def kernel_version():
|
651 |
+
"""Return a tuple such as (2, 6, 36)."""
|
652 |
+
if not POSIX:
|
653 |
+
raise NotImplementedError("not POSIX")
|
654 |
+
s = ""
|
655 |
+
uname = os.uname()[2]
|
656 |
+
for c in uname:
|
657 |
+
if c.isdigit() or c == '.':
|
658 |
+
s += c
|
659 |
+
else:
|
660 |
+
break
|
661 |
+
if not s:
|
662 |
+
raise ValueError("can't parse %r" % uname)
|
663 |
+
minor = 0
|
664 |
+
micro = 0
|
665 |
+
nums = s.split('.')
|
666 |
+
major = int(nums[0])
|
667 |
+
if len(nums) >= 2:
|
668 |
+
minor = int(nums[1])
|
669 |
+
if len(nums) >= 3:
|
670 |
+
micro = int(nums[2])
|
671 |
+
return (major, minor, micro)
|
672 |
+
|
673 |
+
|
674 |
+
def get_winver():
|
675 |
+
if not WINDOWS:
|
676 |
+
raise NotImplementedError("not WINDOWS")
|
677 |
+
wv = sys.getwindowsversion()
|
678 |
+
if hasattr(wv, 'service_pack_major'): # python >= 2.7
|
679 |
+
sp = wv.service_pack_major or 0
|
680 |
+
else:
|
681 |
+
r = re.search(r"\s\d$", wv[4])
|
682 |
+
sp = int(r.group(0)) if r else 0
|
683 |
+
return (wv[0], wv[1], sp)
|
684 |
+
|
685 |
+
|
686 |
+
# ===================================================================
|
687 |
+
# --- sync primitives
|
688 |
+
# ===================================================================
|
689 |
+
|
690 |
+
|
691 |
+
class retry:
|
692 |
+
"""A retry decorator."""
|
693 |
+
|
694 |
+
def __init__(
|
695 |
+
self,
|
696 |
+
exception=Exception,
|
697 |
+
timeout=None,
|
698 |
+
retries=None,
|
699 |
+
interval=0.001,
|
700 |
+
logfun=None,
|
701 |
+
):
|
702 |
+
if timeout and retries:
|
703 |
+
raise ValueError("timeout and retries args are mutually exclusive")
|
704 |
+
self.exception = exception
|
705 |
+
self.timeout = timeout
|
706 |
+
self.retries = retries
|
707 |
+
self.interval = interval
|
708 |
+
self.logfun = logfun
|
709 |
+
|
710 |
+
def __iter__(self):
|
711 |
+
if self.timeout:
|
712 |
+
stop_at = time.time() + self.timeout
|
713 |
+
while time.time() < stop_at:
|
714 |
+
yield
|
715 |
+
elif self.retries:
|
716 |
+
for _ in range(self.retries):
|
717 |
+
yield
|
718 |
+
else:
|
719 |
+
while True:
|
720 |
+
yield
|
721 |
+
|
722 |
+
def sleep(self):
|
723 |
+
if self.interval is not None:
|
724 |
+
time.sleep(self.interval)
|
725 |
+
|
726 |
+
def __call__(self, fun):
|
727 |
+
@functools.wraps(fun)
|
728 |
+
def wrapper(*args, **kwargs):
|
729 |
+
exc = None
|
730 |
+
for _ in self:
|
731 |
+
try:
|
732 |
+
return fun(*args, **kwargs)
|
733 |
+
except self.exception as _: # NOQA
|
734 |
+
exc = _
|
735 |
+
if self.logfun is not None:
|
736 |
+
self.logfun(exc)
|
737 |
+
self.sleep()
|
738 |
+
continue
|
739 |
+
if PY3:
|
740 |
+
raise exc
|
741 |
+
else:
|
742 |
+
raise
|
743 |
+
|
744 |
+
# This way the user of the decorated function can change config
|
745 |
+
# parameters.
|
746 |
+
wrapper.decorator = self
|
747 |
+
return wrapper
|
748 |
+
|
749 |
+
|
750 |
+
@retry(
|
751 |
+
exception=psutil.NoSuchProcess,
|
752 |
+
logfun=None,
|
753 |
+
timeout=GLOBAL_TIMEOUT,
|
754 |
+
interval=0.001,
|
755 |
+
)
|
756 |
+
def wait_for_pid(pid):
|
757 |
+
"""Wait for pid to show up in the process list then return.
|
758 |
+
Used in the test suite to give time the sub process to initialize.
|
759 |
+
"""
|
760 |
+
if pid not in psutil.pids():
|
761 |
+
raise psutil.NoSuchProcess(pid)
|
762 |
+
psutil.Process(pid)
|
763 |
+
|
764 |
+
|
765 |
+
@retry(
|
766 |
+
exception=(FileNotFoundError, AssertionError),
|
767 |
+
logfun=None,
|
768 |
+
timeout=GLOBAL_TIMEOUT,
|
769 |
+
interval=0.001,
|
770 |
+
)
|
771 |
+
def wait_for_file(fname, delete=True, empty=False):
|
772 |
+
"""Wait for a file to be written on disk with some content."""
|
773 |
+
with open(fname, "rb") as f:
|
774 |
+
data = f.read()
|
775 |
+
if not empty:
|
776 |
+
assert data
|
777 |
+
if delete:
|
778 |
+
safe_rmpath(fname)
|
779 |
+
return data
|
780 |
+
|
781 |
+
|
782 |
+
@retry(
|
783 |
+
exception=AssertionError,
|
784 |
+
logfun=None,
|
785 |
+
timeout=GLOBAL_TIMEOUT,
|
786 |
+
interval=0.001,
|
787 |
+
)
|
788 |
+
def call_until(fun, expr):
|
789 |
+
"""Keep calling function for timeout secs and exit if eval()
|
790 |
+
expression is True.
|
791 |
+
"""
|
792 |
+
ret = fun()
|
793 |
+
assert eval(expr) # noqa
|
794 |
+
return ret
|
795 |
+
|
796 |
+
|
797 |
+
# ===================================================================
|
798 |
+
# --- fs
|
799 |
+
# ===================================================================
|
800 |
+
|
801 |
+
|
802 |
+
def safe_rmpath(path):
|
803 |
+
"""Convenience function for removing temporary test files or dirs."""
|
804 |
+
|
805 |
+
def retry_fun(fun):
|
806 |
+
# On Windows it could happen that the file or directory has
|
807 |
+
# open handles or references preventing the delete operation
|
808 |
+
# to succeed immediately, so we retry for a while. See:
|
809 |
+
# https://bugs.python.org/issue33240
|
810 |
+
stop_at = time.time() + GLOBAL_TIMEOUT
|
811 |
+
while time.time() < stop_at:
|
812 |
+
try:
|
813 |
+
return fun()
|
814 |
+
except FileNotFoundError:
|
815 |
+
pass
|
816 |
+
except WindowsError as _:
|
817 |
+
err = _
|
818 |
+
warn("ignoring %s" % (str(err)))
|
819 |
+
time.sleep(0.01)
|
820 |
+
raise err
|
821 |
+
|
822 |
+
try:
|
823 |
+
st = os.stat(path)
|
824 |
+
if stat.S_ISDIR(st.st_mode):
|
825 |
+
fun = functools.partial(shutil.rmtree, path)
|
826 |
+
else:
|
827 |
+
fun = functools.partial(os.remove, path)
|
828 |
+
if POSIX:
|
829 |
+
fun()
|
830 |
+
else:
|
831 |
+
retry_fun(fun)
|
832 |
+
except FileNotFoundError:
|
833 |
+
pass
|
834 |
+
|
835 |
+
|
836 |
+
def safe_mkdir(dir):
|
837 |
+
"""Convenience function for creating a directory."""
|
838 |
+
try:
|
839 |
+
os.mkdir(dir)
|
840 |
+
except FileExistsError:
|
841 |
+
pass
|
842 |
+
|
843 |
+
|
844 |
+
@contextlib.contextmanager
|
845 |
+
def chdir(dirname):
|
846 |
+
"""Context manager which temporarily changes the current directory."""
|
847 |
+
curdir = os.getcwd()
|
848 |
+
try:
|
849 |
+
os.chdir(dirname)
|
850 |
+
yield
|
851 |
+
finally:
|
852 |
+
os.chdir(curdir)
|
853 |
+
|
854 |
+
|
855 |
+
def create_py_exe(path):
|
856 |
+
"""Create a Python executable file in the given location."""
|
857 |
+
assert not os.path.exists(path), path
|
858 |
+
atexit.register(safe_rmpath, path)
|
859 |
+
shutil.copyfile(PYTHON_EXE, path)
|
860 |
+
if POSIX:
|
861 |
+
st = os.stat(path)
|
862 |
+
os.chmod(path, st.st_mode | stat.S_IEXEC)
|
863 |
+
return path
|
864 |
+
|
865 |
+
|
866 |
+
def create_c_exe(path, c_code=None):
|
867 |
+
"""Create a compiled C executable in the given location."""
|
868 |
+
assert not os.path.exists(path), path
|
869 |
+
if not which("gcc"):
|
870 |
+
raise unittest.SkipTest("gcc is not installed")
|
871 |
+
if c_code is None:
|
872 |
+
c_code = textwrap.dedent("""
|
873 |
+
#include <unistd.h>
|
874 |
+
int main() {
|
875 |
+
pause();
|
876 |
+
return 1;
|
877 |
+
}
|
878 |
+
""")
|
879 |
+
else:
|
880 |
+
assert isinstance(c_code, str), c_code
|
881 |
+
|
882 |
+
atexit.register(safe_rmpath, path)
|
883 |
+
with open(get_testfn(suffix='.c'), "w") as f:
|
884 |
+
f.write(c_code)
|
885 |
+
try:
|
886 |
+
subprocess.check_call(["gcc", f.name, "-o", path])
|
887 |
+
finally:
|
888 |
+
safe_rmpath(f.name)
|
889 |
+
return path
|
890 |
+
|
891 |
+
|
892 |
+
def get_testfn(suffix="", dir=None):
|
893 |
+
"""Return an absolute pathname of a file or dir that did not
|
894 |
+
exist at the time this call is made. Also schedule it for safe
|
895 |
+
deletion at interpreter exit. It's technically racy but probably
|
896 |
+
not really due to the time variant.
|
897 |
+
"""
|
898 |
+
while True:
|
899 |
+
name = tempfile.mktemp(prefix=TESTFN_PREFIX, suffix=suffix, dir=dir)
|
900 |
+
if not os.path.exists(name): # also include dirs
|
901 |
+
path = os.path.realpath(name) # needed for OSX
|
902 |
+
atexit.register(safe_rmpath, path)
|
903 |
+
return path
|
904 |
+
|
905 |
+
|
906 |
+
# ===================================================================
|
907 |
+
# --- testing
|
908 |
+
# ===================================================================
|
909 |
+
|
910 |
+
|
911 |
+
class TestCase(unittest.TestCase):
|
912 |
+
|
913 |
+
# Print a full path representation of the single unit tests
|
914 |
+
# being run.
|
915 |
+
def __str__(self):
|
916 |
+
fqmod = self.__class__.__module__
|
917 |
+
if not fqmod.startswith('psutil.'):
|
918 |
+
fqmod = 'psutil.tests.' + fqmod
|
919 |
+
return "%s.%s.%s" % (
|
920 |
+
fqmod,
|
921 |
+
self.__class__.__name__,
|
922 |
+
self._testMethodName,
|
923 |
+
)
|
924 |
+
|
925 |
+
# assertRaisesRegexp renamed to assertRaisesRegex in 3.3;
|
926 |
+
# add support for the new name.
|
927 |
+
if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
|
928 |
+
assertRaisesRegex = unittest.TestCase.assertRaisesRegexp # noqa
|
929 |
+
|
930 |
+
# ...otherwise multiprocessing.Pool complains
|
931 |
+
if not PY3:
|
932 |
+
|
933 |
+
def runTest(self):
|
934 |
+
pass
|
935 |
+
|
936 |
+
@contextlib.contextmanager
|
937 |
+
def subTest(self, *args, **kw):
|
938 |
+
# fake it for python 2.7
|
939 |
+
yield
|
940 |
+
|
941 |
+
|
942 |
+
# monkey patch default unittest.TestCase
|
943 |
+
unittest.TestCase = TestCase
|
944 |
+
|
945 |
+
|
946 |
+
class PsutilTestCase(TestCase):
|
947 |
+
"""Test class providing auto-cleanup wrappers on top of process
|
948 |
+
test utilities.
|
949 |
+
"""
|
950 |
+
|
951 |
+
def get_testfn(self, suffix="", dir=None):
|
952 |
+
fname = get_testfn(suffix=suffix, dir=dir)
|
953 |
+
self.addCleanup(safe_rmpath, fname)
|
954 |
+
return fname
|
955 |
+
|
956 |
+
def spawn_testproc(self, *args, **kwds):
|
957 |
+
sproc = spawn_testproc(*args, **kwds)
|
958 |
+
self.addCleanup(terminate, sproc)
|
959 |
+
return sproc
|
960 |
+
|
961 |
+
def spawn_children_pair(self):
|
962 |
+
child1, child2 = spawn_children_pair()
|
963 |
+
self.addCleanup(terminate, child2)
|
964 |
+
self.addCleanup(terminate, child1) # executed first
|
965 |
+
return (child1, child2)
|
966 |
+
|
967 |
+
def spawn_zombie(self):
|
968 |
+
parent, zombie = spawn_zombie()
|
969 |
+
self.addCleanup(terminate, zombie)
|
970 |
+
self.addCleanup(terminate, parent) # executed first
|
971 |
+
return (parent, zombie)
|
972 |
+
|
973 |
+
def pyrun(self, *args, **kwds):
|
974 |
+
sproc, srcfile = pyrun(*args, **kwds)
|
975 |
+
self.addCleanup(safe_rmpath, srcfile)
|
976 |
+
self.addCleanup(terminate, sproc) # executed first
|
977 |
+
return sproc
|
978 |
+
|
979 |
+
def _check_proc_exc(self, proc, exc):
|
980 |
+
self.assertIsInstance(exc, psutil.Error)
|
981 |
+
self.assertEqual(exc.pid, proc.pid)
|
982 |
+
self.assertEqual(exc.name, proc._name)
|
983 |
+
if exc.name:
|
984 |
+
self.assertNotEqual(exc.name, "")
|
985 |
+
if isinstance(exc, psutil.ZombieProcess):
|
986 |
+
self.assertEqual(exc.ppid, proc._ppid)
|
987 |
+
if exc.ppid is not None:
|
988 |
+
self.assertGreaterEqual(exc.ppid, 0)
|
989 |
+
str(exc)
|
990 |
+
repr(exc)
|
991 |
+
|
992 |
+
def assertPidGone(self, pid):
|
993 |
+
with self.assertRaises(psutil.NoSuchProcess) as cm:
|
994 |
+
try:
|
995 |
+
psutil.Process(pid)
|
996 |
+
except psutil.ZombieProcess:
|
997 |
+
raise AssertionError("wasn't supposed to raise ZombieProcess")
|
998 |
+
self.assertEqual(cm.exception.pid, pid)
|
999 |
+
self.assertEqual(cm.exception.name, None)
|
1000 |
+
assert not psutil.pid_exists(pid), pid
|
1001 |
+
self.assertNotIn(pid, psutil.pids())
|
1002 |
+
self.assertNotIn(pid, [x.pid for x in psutil.process_iter()])
|
1003 |
+
|
1004 |
+
def assertProcessGone(self, proc):
|
1005 |
+
self.assertPidGone(proc.pid)
|
1006 |
+
ns = process_namespace(proc)
|
1007 |
+
for fun, name in ns.iter(ns.all, clear_cache=True):
|
1008 |
+
with self.subTest(proc=proc, name=name):
|
1009 |
+
try:
|
1010 |
+
ret = fun()
|
1011 |
+
except psutil.ZombieProcess:
|
1012 |
+
raise
|
1013 |
+
except psutil.NoSuchProcess as exc:
|
1014 |
+
self._check_proc_exc(proc, exc)
|
1015 |
+
else:
|
1016 |
+
msg = "Process.%s() didn't raise NSP and returned %r" % (
|
1017 |
+
name,
|
1018 |
+
ret,
|
1019 |
+
)
|
1020 |
+
raise AssertionError(msg)
|
1021 |
+
proc.wait(timeout=0) # assert not raise TimeoutExpired
|
1022 |
+
|
1023 |
+
def assertProcessZombie(self, proc):
|
1024 |
+
# A zombie process should always be instantiable.
|
1025 |
+
clone = psutil.Process(proc.pid)
|
1026 |
+
# Cloned zombie on Open/NetBSD has null creation time, see:
|
1027 |
+
# https://github.com/giampaolo/psutil/issues/2287
|
1028 |
+
self.assertEqual(proc, clone)
|
1029 |
+
if not (OPENBSD or NETBSD):
|
1030 |
+
self.assertEqual(hash(proc), hash(clone))
|
1031 |
+
# Its status always be querable.
|
1032 |
+
self.assertEqual(proc.status(), psutil.STATUS_ZOMBIE)
|
1033 |
+
# It should be considered 'running'.
|
1034 |
+
assert proc.is_running()
|
1035 |
+
assert psutil.pid_exists(proc.pid)
|
1036 |
+
# as_dict() shouldn't crash.
|
1037 |
+
proc.as_dict()
|
1038 |
+
# It should show up in pids() and process_iter().
|
1039 |
+
self.assertIn(proc.pid, psutil.pids())
|
1040 |
+
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
|
1041 |
+
psutil._pmap = {}
|
1042 |
+
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
|
1043 |
+
# Call all methods.
|
1044 |
+
ns = process_namespace(proc)
|
1045 |
+
for fun, name in ns.iter(ns.all, clear_cache=True):
|
1046 |
+
with self.subTest(proc=proc, name=name):
|
1047 |
+
try:
|
1048 |
+
fun()
|
1049 |
+
except (psutil.ZombieProcess, psutil.AccessDenied) as exc:
|
1050 |
+
self._check_proc_exc(proc, exc)
|
1051 |
+
if LINUX:
|
1052 |
+
# https://github.com/giampaolo/psutil/pull/2288
|
1053 |
+
with self.assertRaises(psutil.ZombieProcess) as cm:
|
1054 |
+
proc.cmdline()
|
1055 |
+
self._check_proc_exc(proc, cm.exception)
|
1056 |
+
with self.assertRaises(psutil.ZombieProcess) as cm:
|
1057 |
+
proc.exe()
|
1058 |
+
self._check_proc_exc(proc, cm.exception)
|
1059 |
+
with self.assertRaises(psutil.ZombieProcess) as cm:
|
1060 |
+
proc.memory_maps()
|
1061 |
+
self._check_proc_exc(proc, cm.exception)
|
1062 |
+
# Zombie cannot be signaled or terminated.
|
1063 |
+
proc.suspend()
|
1064 |
+
proc.resume()
|
1065 |
+
proc.terminate()
|
1066 |
+
proc.kill()
|
1067 |
+
assert proc.is_running()
|
1068 |
+
assert psutil.pid_exists(proc.pid)
|
1069 |
+
self.assertIn(proc.pid, psutil.pids())
|
1070 |
+
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
|
1071 |
+
psutil._pmap = {}
|
1072 |
+
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
|
1073 |
+
|
1074 |
+
# Its parent should 'see' it (edit: not true on BSD and MACOS).
|
1075 |
+
# descendants = [x.pid for x in psutil.Process().children(
|
1076 |
+
# recursive=True)]
|
1077 |
+
# self.assertIn(proc.pid, descendants)
|
1078 |
+
|
1079 |
+
# __eq__ can't be relied upon because creation time may not be
|
1080 |
+
# querable.
|
1081 |
+
# self.assertEqual(proc, psutil.Process(proc.pid))
|
1082 |
+
|
1083 |
+
# XXX should we also assume ppid() to be usable? Note: this
|
1084 |
+
# would be an important use case as the only way to get
|
1085 |
+
# rid of a zombie is to kill its parent.
|
1086 |
+
# self.assertEqual(proc.ppid(), os.getpid())
|
1087 |
+
|
1088 |
+
|
1089 |
+
@unittest.skipIf(PYPY, "unreliable on PYPY")
|
1090 |
+
class TestMemoryLeak(PsutilTestCase):
|
1091 |
+
"""Test framework class for detecting function memory leaks,
|
1092 |
+
typically functions implemented in C which forgot to free() memory
|
1093 |
+
from the heap. It does so by checking whether the process memory
|
1094 |
+
usage increased before and after calling the function many times.
|
1095 |
+
|
1096 |
+
Note that this is hard (probably impossible) to do reliably, due
|
1097 |
+
to how the OS handles memory, the GC and so on (memory can even
|
1098 |
+
decrease!). In order to avoid false positives, in case of failure
|
1099 |
+
(mem > 0) we retry the test for up to 5 times, increasing call
|
1100 |
+
repetitions each time. If the memory keeps increasing then it's a
|
1101 |
+
failure.
|
1102 |
+
|
1103 |
+
If available (Linux, OSX, Windows), USS memory is used for comparison,
|
1104 |
+
since it's supposed to be more precise, see:
|
1105 |
+
https://gmpy.dev/blog/2016/real-process-memory-and-environ-in-python
|
1106 |
+
If not, RSS memory is used. mallinfo() on Linux and _heapwalk() on
|
1107 |
+
Windows may give even more precision, but at the moment are not
|
1108 |
+
implemented.
|
1109 |
+
|
1110 |
+
PyPy appears to be completely unstable for this framework, probably
|
1111 |
+
because of its JIT, so tests on PYPY are skipped.
|
1112 |
+
|
1113 |
+
Usage:
|
1114 |
+
|
1115 |
+
class TestLeaks(psutil.tests.TestMemoryLeak):
|
1116 |
+
|
1117 |
+
def test_fun(self):
|
1118 |
+
self.execute(some_function)
|
1119 |
+
"""
|
1120 |
+
|
1121 |
+
# Configurable class attrs.
|
1122 |
+
times = 200
|
1123 |
+
warmup_times = 10
|
1124 |
+
tolerance = 0 # memory
|
1125 |
+
retries = 10 if CI_TESTING else 5
|
1126 |
+
verbose = True
|
1127 |
+
_thisproc = psutil.Process()
|
1128 |
+
_psutil_debug_orig = bool(os.getenv('PSUTIL_DEBUG'))
|
1129 |
+
|
1130 |
+
@classmethod
|
1131 |
+
def setUpClass(cls):
|
1132 |
+
psutil._set_debug(False) # avoid spamming to stderr
|
1133 |
+
|
1134 |
+
@classmethod
|
1135 |
+
def tearDownClass(cls):
|
1136 |
+
psutil._set_debug(cls._psutil_debug_orig)
|
1137 |
+
|
1138 |
+
def _get_mem(self):
|
1139 |
+
# USS is the closest thing we have to "real" memory usage and it
|
1140 |
+
# should be less likely to produce false positives.
|
1141 |
+
mem = self._thisproc.memory_full_info()
|
1142 |
+
return getattr(mem, "uss", mem.rss)
|
1143 |
+
|
1144 |
+
def _get_num_fds(self):
|
1145 |
+
if POSIX:
|
1146 |
+
return self._thisproc.num_fds()
|
1147 |
+
else:
|
1148 |
+
return self._thisproc.num_handles()
|
1149 |
+
|
1150 |
+
def _log(self, msg):
|
1151 |
+
if self.verbose:
|
1152 |
+
print_color(msg, color="yellow", file=sys.stderr)
|
1153 |
+
|
1154 |
+
def _check_fds(self, fun):
|
1155 |
+
"""Makes sure num_fds() (POSIX) or num_handles() (Windows) does
|
1156 |
+
not increase after calling a function. Used to discover forgotten
|
1157 |
+
close(2) and CloseHandle syscalls.
|
1158 |
+
"""
|
1159 |
+
before = self._get_num_fds()
|
1160 |
+
self.call(fun)
|
1161 |
+
after = self._get_num_fds()
|
1162 |
+
diff = after - before
|
1163 |
+
if diff < 0:
|
1164 |
+
raise self.fail(
|
1165 |
+
"negative diff %r (gc probably collected a "
|
1166 |
+
"resource from a previous test)" % diff
|
1167 |
+
)
|
1168 |
+
if diff > 0:
|
1169 |
+
type_ = "fd" if POSIX else "handle"
|
1170 |
+
if diff > 1:
|
1171 |
+
type_ += "s"
|
1172 |
+
msg = "%s unclosed %s after calling %r" % (diff, type_, fun)
|
1173 |
+
raise self.fail(msg)
|
1174 |
+
|
1175 |
+
def _call_ntimes(self, fun, times):
|
1176 |
+
"""Get 2 distinct memory samples, before and after having
|
1177 |
+
called fun repeatedly, and return the memory difference.
|
1178 |
+
"""
|
1179 |
+
gc.collect(generation=1)
|
1180 |
+
mem1 = self._get_mem()
|
1181 |
+
for x in range(times):
|
1182 |
+
ret = self.call(fun)
|
1183 |
+
del x, ret
|
1184 |
+
gc.collect(generation=1)
|
1185 |
+
mem2 = self._get_mem()
|
1186 |
+
self.assertEqual(gc.garbage, [])
|
1187 |
+
diff = mem2 - mem1 # can also be negative
|
1188 |
+
return diff
|
1189 |
+
|
1190 |
+
def _check_mem(self, fun, times, retries, tolerance):
|
1191 |
+
messages = []
|
1192 |
+
prev_mem = 0
|
1193 |
+
increase = times
|
1194 |
+
for idx in range(1, retries + 1):
|
1195 |
+
mem = self._call_ntimes(fun, times)
|
1196 |
+
msg = "Run #%s: extra-mem=%s, per-call=%s, calls=%s" % (
|
1197 |
+
idx,
|
1198 |
+
bytes2human(mem),
|
1199 |
+
bytes2human(mem / times),
|
1200 |
+
times,
|
1201 |
+
)
|
1202 |
+
messages.append(msg)
|
1203 |
+
success = mem <= tolerance or mem <= prev_mem
|
1204 |
+
if success:
|
1205 |
+
if idx > 1:
|
1206 |
+
self._log(msg)
|
1207 |
+
return
|
1208 |
+
else:
|
1209 |
+
if idx == 1:
|
1210 |
+
print() # NOQA
|
1211 |
+
self._log(msg)
|
1212 |
+
times += increase
|
1213 |
+
prev_mem = mem
|
1214 |
+
raise self.fail(". ".join(messages))
|
1215 |
+
|
1216 |
+
# ---
|
1217 |
+
|
1218 |
+
def call(self, fun):
|
1219 |
+
return fun()
|
1220 |
+
|
1221 |
+
def execute(
|
1222 |
+
self, fun, times=None, warmup_times=None, retries=None, tolerance=None
|
1223 |
+
):
|
1224 |
+
"""Test a callable."""
|
1225 |
+
times = times if times is not None else self.times
|
1226 |
+
warmup_times = (
|
1227 |
+
warmup_times if warmup_times is not None else self.warmup_times
|
1228 |
+
)
|
1229 |
+
retries = retries if retries is not None else self.retries
|
1230 |
+
tolerance = tolerance if tolerance is not None else self.tolerance
|
1231 |
+
try:
|
1232 |
+
assert times >= 1, "times must be >= 1"
|
1233 |
+
assert warmup_times >= 0, "warmup_times must be >= 0"
|
1234 |
+
assert retries >= 0, "retries must be >= 0"
|
1235 |
+
assert tolerance >= 0, "tolerance must be >= 0"
|
1236 |
+
except AssertionError as err:
|
1237 |
+
raise ValueError(str(err))
|
1238 |
+
|
1239 |
+
self._call_ntimes(fun, warmup_times) # warm up
|
1240 |
+
self._check_fds(fun)
|
1241 |
+
self._check_mem(fun, times=times, retries=retries, tolerance=tolerance)
|
1242 |
+
|
1243 |
+
def execute_w_exc(self, exc, fun, **kwargs):
|
1244 |
+
"""Convenience method to test a callable while making sure it
|
1245 |
+
raises an exception on every call.
|
1246 |
+
"""
|
1247 |
+
|
1248 |
+
def call():
|
1249 |
+
self.assertRaises(exc, fun)
|
1250 |
+
|
1251 |
+
self.execute(call, **kwargs)
|
1252 |
+
|
1253 |
+
|
1254 |
+
def print_sysinfo():
|
1255 |
+
import collections
|
1256 |
+
import datetime
|
1257 |
+
import getpass
|
1258 |
+
import locale
|
1259 |
+
import pprint
|
1260 |
+
|
1261 |
+
try:
|
1262 |
+
import pip
|
1263 |
+
except ImportError:
|
1264 |
+
pip = None
|
1265 |
+
try:
|
1266 |
+
import wheel
|
1267 |
+
except ImportError:
|
1268 |
+
wheel = None
|
1269 |
+
|
1270 |
+
info = collections.OrderedDict()
|
1271 |
+
|
1272 |
+
# OS
|
1273 |
+
if psutil.LINUX and which('lsb_release'):
|
1274 |
+
info['OS'] = sh('lsb_release -d -s')
|
1275 |
+
elif psutil.OSX:
|
1276 |
+
info['OS'] = 'Darwin %s' % platform.mac_ver()[0]
|
1277 |
+
elif psutil.WINDOWS:
|
1278 |
+
info['OS'] = "Windows " + ' '.join(map(str, platform.win32_ver()))
|
1279 |
+
if hasattr(platform, 'win32_edition'):
|
1280 |
+
info['OS'] += ", " + platform.win32_edition()
|
1281 |
+
else:
|
1282 |
+
info['OS'] = "%s %s" % (platform.system(), platform.version())
|
1283 |
+
info['arch'] = ', '.join(
|
1284 |
+
list(platform.architecture()) + [platform.machine()]
|
1285 |
+
)
|
1286 |
+
if psutil.POSIX:
|
1287 |
+
info['kernel'] = platform.uname()[2]
|
1288 |
+
|
1289 |
+
# python
|
1290 |
+
info['python'] = ', '.join([
|
1291 |
+
platform.python_implementation(),
|
1292 |
+
platform.python_version(),
|
1293 |
+
platform.python_compiler(),
|
1294 |
+
])
|
1295 |
+
info['pip'] = getattr(pip, '__version__', 'not installed')
|
1296 |
+
if wheel is not None:
|
1297 |
+
info['pip'] += " (wheel=%s)" % wheel.__version__
|
1298 |
+
|
1299 |
+
# UNIX
|
1300 |
+
if psutil.POSIX:
|
1301 |
+
if which('gcc'):
|
1302 |
+
out = sh(['gcc', '--version'])
|
1303 |
+
info['gcc'] = str(out).split('\n')[0]
|
1304 |
+
else:
|
1305 |
+
info['gcc'] = 'not installed'
|
1306 |
+
s = platform.libc_ver()[1]
|
1307 |
+
if s:
|
1308 |
+
info['glibc'] = s
|
1309 |
+
|
1310 |
+
# system
|
1311 |
+
info['fs-encoding'] = sys.getfilesystemencoding()
|
1312 |
+
lang = locale.getlocale()
|
1313 |
+
info['lang'] = '%s, %s' % (lang[0], lang[1])
|
1314 |
+
info['boot-time'] = datetime.datetime.fromtimestamp(
|
1315 |
+
psutil.boot_time()
|
1316 |
+
).strftime("%Y-%m-%d %H:%M:%S")
|
1317 |
+
info['time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
1318 |
+
info['user'] = getpass.getuser()
|
1319 |
+
info['home'] = os.path.expanduser("~")
|
1320 |
+
info['cwd'] = os.getcwd()
|
1321 |
+
info['pyexe'] = PYTHON_EXE
|
1322 |
+
info['hostname'] = platform.node()
|
1323 |
+
info['PID'] = os.getpid()
|
1324 |
+
|
1325 |
+
# metrics
|
1326 |
+
info['cpus'] = psutil.cpu_count()
|
1327 |
+
info['loadavg'] = "%.1f%%, %.1f%%, %.1f%%" % (
|
1328 |
+
tuple([x / psutil.cpu_count() * 100 for x in psutil.getloadavg()])
|
1329 |
+
)
|
1330 |
+
mem = psutil.virtual_memory()
|
1331 |
+
info['memory'] = "%s%%, used=%s, total=%s" % (
|
1332 |
+
int(mem.percent),
|
1333 |
+
bytes2human(mem.used),
|
1334 |
+
bytes2human(mem.total),
|
1335 |
+
)
|
1336 |
+
swap = psutil.swap_memory()
|
1337 |
+
info['swap'] = "%s%%, used=%s, total=%s" % (
|
1338 |
+
int(swap.percent),
|
1339 |
+
bytes2human(swap.used),
|
1340 |
+
bytes2human(swap.total),
|
1341 |
+
)
|
1342 |
+
info['pids'] = len(psutil.pids())
|
1343 |
+
pinfo = psutil.Process().as_dict()
|
1344 |
+
pinfo.pop('memory_maps', None)
|
1345 |
+
info['proc'] = pprint.pformat(pinfo)
|
1346 |
+
|
1347 |
+
print("=" * 70, file=sys.stderr) # NOQA
|
1348 |
+
for k, v in info.items():
|
1349 |
+
print("%-17s %s" % (k + ':', v), file=sys.stderr) # NOQA
|
1350 |
+
print("=" * 70, file=sys.stderr) # NOQA
|
1351 |
+
sys.stdout.flush()
|
1352 |
+
|
1353 |
+
if WINDOWS:
|
1354 |
+
os.system("tasklist")
|
1355 |
+
elif which("ps"):
|
1356 |
+
os.system("ps aux")
|
1357 |
+
print("=" * 70, file=sys.stderr) # NOQA
|
1358 |
+
sys.stdout.flush()
|
1359 |
+
|
1360 |
+
|
1361 |
+
def is_win_secure_system_proc(pid):
|
1362 |
+
# see: https://github.com/giampaolo/psutil/issues/2338
|
1363 |
+
@memoize
|
1364 |
+
def get_procs():
|
1365 |
+
ret = {}
|
1366 |
+
out = sh("tasklist.exe /NH /FO csv")
|
1367 |
+
for line in out.splitlines()[1:]:
|
1368 |
+
bits = [x.replace('"', "") for x in line.split(",")]
|
1369 |
+
name, pid = bits[0], int(bits[1])
|
1370 |
+
ret[pid] = name
|
1371 |
+
return ret
|
1372 |
+
|
1373 |
+
try:
|
1374 |
+
return get_procs()[pid] == "Secure System"
|
1375 |
+
except KeyError:
|
1376 |
+
return False
|
1377 |
+
|
1378 |
+
|
1379 |
+
def _get_eligible_cpu():
|
1380 |
+
p = psutil.Process()
|
1381 |
+
if hasattr(p, "cpu_num"):
|
1382 |
+
return p.cpu_num()
|
1383 |
+
elif hasattr(p, "cpu_affinity"):
|
1384 |
+
return random.choice(p.cpu_affinity())
|
1385 |
+
return 0
|
1386 |
+
|
1387 |
+
|
1388 |
+
class process_namespace:
|
1389 |
+
"""A container that lists all Process class method names + some
|
1390 |
+
reasonable parameters to be called with. Utility methods (parent(),
|
1391 |
+
children(), ...) are excluded.
|
1392 |
+
|
1393 |
+
>>> ns = process_namespace(psutil.Process())
|
1394 |
+
>>> for fun, name in ns.iter(ns.getters):
|
1395 |
+
... fun()
|
1396 |
+
"""
|
1397 |
+
|
1398 |
+
utils = [('cpu_percent', (), {}), ('memory_percent', (), {})]
|
1399 |
+
|
1400 |
+
ignored = [
|
1401 |
+
('as_dict', (), {}),
|
1402 |
+
('children', (), {'recursive': True}),
|
1403 |
+
('is_running', (), {}),
|
1404 |
+
('memory_info_ex', (), {}),
|
1405 |
+
('oneshot', (), {}),
|
1406 |
+
('parent', (), {}),
|
1407 |
+
('parents', (), {}),
|
1408 |
+
('pid', (), {}),
|
1409 |
+
('wait', (0,), {}),
|
1410 |
+
]
|
1411 |
+
|
1412 |
+
getters = [
|
1413 |
+
('cmdline', (), {}),
|
1414 |
+
('connections', (), {'kind': 'all'}),
|
1415 |
+
('cpu_times', (), {}),
|
1416 |
+
('create_time', (), {}),
|
1417 |
+
('cwd', (), {}),
|
1418 |
+
('exe', (), {}),
|
1419 |
+
('memory_full_info', (), {}),
|
1420 |
+
('memory_info', (), {}),
|
1421 |
+
('name', (), {}),
|
1422 |
+
('nice', (), {}),
|
1423 |
+
('num_ctx_switches', (), {}),
|
1424 |
+
('num_threads', (), {}),
|
1425 |
+
('open_files', (), {}),
|
1426 |
+
('ppid', (), {}),
|
1427 |
+
('status', (), {}),
|
1428 |
+
('threads', (), {}),
|
1429 |
+
('username', (), {}),
|
1430 |
+
]
|
1431 |
+
if POSIX:
|
1432 |
+
getters += [('uids', (), {})]
|
1433 |
+
getters += [('gids', (), {})]
|
1434 |
+
getters += [('terminal', (), {})]
|
1435 |
+
getters += [('num_fds', (), {})]
|
1436 |
+
if HAS_PROC_IO_COUNTERS:
|
1437 |
+
getters += [('io_counters', (), {})]
|
1438 |
+
if HAS_IONICE:
|
1439 |
+
getters += [('ionice', (), {})]
|
1440 |
+
if HAS_RLIMIT:
|
1441 |
+
getters += [('rlimit', (psutil.RLIMIT_NOFILE,), {})]
|
1442 |
+
if HAS_CPU_AFFINITY:
|
1443 |
+
getters += [('cpu_affinity', (), {})]
|
1444 |
+
if HAS_PROC_CPU_NUM:
|
1445 |
+
getters += [('cpu_num', (), {})]
|
1446 |
+
if HAS_ENVIRON:
|
1447 |
+
getters += [('environ', (), {})]
|
1448 |
+
if WINDOWS:
|
1449 |
+
getters += [('num_handles', (), {})]
|
1450 |
+
if HAS_MEMORY_MAPS:
|
1451 |
+
getters += [('memory_maps', (), {'grouped': False})]
|
1452 |
+
|
1453 |
+
setters = []
|
1454 |
+
if POSIX:
|
1455 |
+
setters += [('nice', (0,), {})]
|
1456 |
+
else:
|
1457 |
+
setters += [('nice', (psutil.NORMAL_PRIORITY_CLASS,), {})]
|
1458 |
+
if HAS_RLIMIT:
|
1459 |
+
setters += [('rlimit', (psutil.RLIMIT_NOFILE, (1024, 4096)), {})]
|
1460 |
+
if HAS_IONICE:
|
1461 |
+
if LINUX:
|
1462 |
+
setters += [('ionice', (psutil.IOPRIO_CLASS_NONE, 0), {})]
|
1463 |
+
else:
|
1464 |
+
setters += [('ionice', (psutil.IOPRIO_NORMAL,), {})]
|
1465 |
+
if HAS_CPU_AFFINITY:
|
1466 |
+
setters += [('cpu_affinity', ([_get_eligible_cpu()],), {})]
|
1467 |
+
|
1468 |
+
killers = [
|
1469 |
+
('send_signal', (signal.SIGTERM,), {}),
|
1470 |
+
('suspend', (), {}),
|
1471 |
+
('resume', (), {}),
|
1472 |
+
('terminate', (), {}),
|
1473 |
+
('kill', (), {}),
|
1474 |
+
]
|
1475 |
+
if WINDOWS:
|
1476 |
+
killers += [('send_signal', (signal.CTRL_C_EVENT,), {})]
|
1477 |
+
killers += [('send_signal', (signal.CTRL_BREAK_EVENT,), {})]
|
1478 |
+
|
1479 |
+
all = utils + getters + setters + killers
|
1480 |
+
|
1481 |
+
def __init__(self, proc):
|
1482 |
+
self._proc = proc
|
1483 |
+
|
1484 |
+
def iter(self, ls, clear_cache=True):
|
1485 |
+
"""Given a list of tuples yields a set of (fun, fun_name) tuples
|
1486 |
+
in random order.
|
1487 |
+
"""
|
1488 |
+
ls = list(ls)
|
1489 |
+
random.shuffle(ls)
|
1490 |
+
for fun_name, args, kwds in ls:
|
1491 |
+
if clear_cache:
|
1492 |
+
self.clear_cache()
|
1493 |
+
fun = getattr(self._proc, fun_name)
|
1494 |
+
fun = functools.partial(fun, *args, **kwds)
|
1495 |
+
yield (fun, fun_name)
|
1496 |
+
|
1497 |
+
def clear_cache(self):
|
1498 |
+
"""Clear the cache of a Process instance."""
|
1499 |
+
self._proc._init(self._proc.pid, _ignore_nsp=True)
|
1500 |
+
|
1501 |
+
@classmethod
|
1502 |
+
def test_class_coverage(cls, test_class, ls):
|
1503 |
+
"""Given a TestCase instance and a list of tuples checks that
|
1504 |
+
the class defines the required test method names.
|
1505 |
+
"""
|
1506 |
+
for fun_name, _, _ in ls:
|
1507 |
+
meth_name = 'test_' + fun_name
|
1508 |
+
if not hasattr(test_class, meth_name):
|
1509 |
+
msg = "%r class should define a '%s' method" % (
|
1510 |
+
test_class.__class__.__name__,
|
1511 |
+
meth_name,
|
1512 |
+
)
|
1513 |
+
raise AttributeError(msg)
|
1514 |
+
|
1515 |
+
@classmethod
|
1516 |
+
def test(cls):
|
1517 |
+
this = set([x[0] for x in cls.all])
|
1518 |
+
ignored = set([x[0] for x in cls.ignored])
|
1519 |
+
klass = set([x for x in dir(psutil.Process) if x[0] != '_'])
|
1520 |
+
leftout = (this | ignored) ^ klass
|
1521 |
+
if leftout:
|
1522 |
+
raise ValueError("uncovered Process class names: %r" % leftout)
|
1523 |
+
|
1524 |
+
|
1525 |
+
class system_namespace:
|
1526 |
+
"""A container that lists all the module-level, system-related APIs.
|
1527 |
+
Utilities such as cpu_percent() are excluded. Usage:
|
1528 |
+
|
1529 |
+
>>> ns = system_namespace
|
1530 |
+
>>> for fun, name in ns.iter(ns.getters):
|
1531 |
+
... fun()
|
1532 |
+
"""
|
1533 |
+
|
1534 |
+
getters = [
|
1535 |
+
('boot_time', (), {}),
|
1536 |
+
('cpu_count', (), {'logical': False}),
|
1537 |
+
('cpu_count', (), {'logical': True}),
|
1538 |
+
('cpu_stats', (), {}),
|
1539 |
+
('cpu_times', (), {'percpu': False}),
|
1540 |
+
('cpu_times', (), {'percpu': True}),
|
1541 |
+
('disk_io_counters', (), {'perdisk': True}),
|
1542 |
+
('disk_partitions', (), {'all': True}),
|
1543 |
+
('disk_usage', (os.getcwd(),), {}),
|
1544 |
+
('net_connections', (), {'kind': 'all'}),
|
1545 |
+
('net_if_addrs', (), {}),
|
1546 |
+
('net_if_stats', (), {}),
|
1547 |
+
('net_io_counters', (), {'pernic': True}),
|
1548 |
+
('pid_exists', (os.getpid(),), {}),
|
1549 |
+
('pids', (), {}),
|
1550 |
+
('swap_memory', (), {}),
|
1551 |
+
('users', (), {}),
|
1552 |
+
('virtual_memory', (), {}),
|
1553 |
+
]
|
1554 |
+
if HAS_CPU_FREQ:
|
1555 |
+
getters += [('cpu_freq', (), {'percpu': True})]
|
1556 |
+
if HAS_GETLOADAVG:
|
1557 |
+
getters += [('getloadavg', (), {})]
|
1558 |
+
if HAS_SENSORS_TEMPERATURES:
|
1559 |
+
getters += [('sensors_temperatures', (), {})]
|
1560 |
+
if HAS_SENSORS_FANS:
|
1561 |
+
getters += [('sensors_fans', (), {})]
|
1562 |
+
if HAS_SENSORS_BATTERY:
|
1563 |
+
getters += [('sensors_battery', (), {})]
|
1564 |
+
if WINDOWS:
|
1565 |
+
getters += [('win_service_iter', (), {})]
|
1566 |
+
getters += [('win_service_get', ('alg',), {})]
|
1567 |
+
|
1568 |
+
ignored = [
|
1569 |
+
('process_iter', (), {}),
|
1570 |
+
('wait_procs', ([psutil.Process()],), {}),
|
1571 |
+
('cpu_percent', (), {}),
|
1572 |
+
('cpu_times_percent', (), {}),
|
1573 |
+
]
|
1574 |
+
|
1575 |
+
all = getters
|
1576 |
+
|
1577 |
+
@staticmethod
|
1578 |
+
def iter(ls):
|
1579 |
+
"""Given a list of tuples yields a set of (fun, fun_name) tuples
|
1580 |
+
in random order.
|
1581 |
+
"""
|
1582 |
+
ls = list(ls)
|
1583 |
+
random.shuffle(ls)
|
1584 |
+
for fun_name, args, kwds in ls:
|
1585 |
+
fun = getattr(psutil, fun_name)
|
1586 |
+
fun = functools.partial(fun, *args, **kwds)
|
1587 |
+
yield (fun, fun_name)
|
1588 |
+
|
1589 |
+
test_class_coverage = process_namespace.test_class_coverage
|
1590 |
+
|
1591 |
+
|
1592 |
+
def serialrun(klass):
|
1593 |
+
"""A decorator to mark a TestCase class. When running parallel tests,
|
1594 |
+
class' unit tests will be run serially (1 process).
|
1595 |
+
"""
|
1596 |
+
# assert issubclass(klass, unittest.TestCase), klass
|
1597 |
+
assert inspect.isclass(klass), klass
|
1598 |
+
klass._serialrun = True
|
1599 |
+
return klass
|
1600 |
+
|
1601 |
+
|
1602 |
+
def retry_on_failure(retries=NO_RETRIES):
|
1603 |
+
"""Decorator which runs a test function and retries N times before
|
1604 |
+
actually failing.
|
1605 |
+
"""
|
1606 |
+
|
1607 |
+
def logfun(exc):
|
1608 |
+
print("%r, retrying" % exc, file=sys.stderr) # NOQA
|
1609 |
+
|
1610 |
+
return retry(
|
1611 |
+
exception=AssertionError, timeout=None, retries=retries, logfun=logfun
|
1612 |
+
)
|
1613 |
+
|
1614 |
+
|
1615 |
+
def skip_on_access_denied(only_if=None):
|
1616 |
+
"""Decorator to Ignore AccessDenied exceptions."""
|
1617 |
+
|
1618 |
+
def decorator(fun):
|
1619 |
+
@functools.wraps(fun)
|
1620 |
+
def wrapper(*args, **kwargs):
|
1621 |
+
try:
|
1622 |
+
return fun(*args, **kwargs)
|
1623 |
+
except psutil.AccessDenied:
|
1624 |
+
if only_if is not None:
|
1625 |
+
if not only_if:
|
1626 |
+
raise
|
1627 |
+
raise unittest.SkipTest("raises AccessDenied")
|
1628 |
+
|
1629 |
+
return wrapper
|
1630 |
+
|
1631 |
+
return decorator
|
1632 |
+
|
1633 |
+
|
1634 |
+
def skip_on_not_implemented(only_if=None):
|
1635 |
+
"""Decorator to Ignore NotImplementedError exceptions."""
|
1636 |
+
|
1637 |
+
def decorator(fun):
|
1638 |
+
@functools.wraps(fun)
|
1639 |
+
def wrapper(*args, **kwargs):
|
1640 |
+
try:
|
1641 |
+
return fun(*args, **kwargs)
|
1642 |
+
except NotImplementedError:
|
1643 |
+
if only_if is not None:
|
1644 |
+
if not only_if:
|
1645 |
+
raise
|
1646 |
+
msg = (
|
1647 |
+
"%r was skipped because it raised NotImplementedError"
|
1648 |
+
% fun.__name__
|
1649 |
+
)
|
1650 |
+
raise unittest.SkipTest(msg)
|
1651 |
+
|
1652 |
+
return wrapper
|
1653 |
+
|
1654 |
+
return decorator
|
1655 |
+
|
1656 |
+
|
1657 |
+
# ===================================================================
|
1658 |
+
# --- network
|
1659 |
+
# ===================================================================
|
1660 |
+
|
1661 |
+
|
1662 |
+
# XXX: no longer used
|
1663 |
+
def get_free_port(host='127.0.0.1'):
|
1664 |
+
"""Return an unused TCP port. Subject to race conditions."""
|
1665 |
+
with contextlib.closing(socket.socket()) as sock:
|
1666 |
+
sock.bind((host, 0))
|
1667 |
+
return sock.getsockname()[1]
|
1668 |
+
|
1669 |
+
|
1670 |
+
def bind_socket(family=AF_INET, type=SOCK_STREAM, addr=None):
|
1671 |
+
"""Binds a generic socket."""
|
1672 |
+
if addr is None and family in (AF_INET, AF_INET6):
|
1673 |
+
addr = ("", 0)
|
1674 |
+
sock = socket.socket(family, type)
|
1675 |
+
try:
|
1676 |
+
if os.name not in ('nt', 'cygwin'):
|
1677 |
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
1678 |
+
sock.bind(addr)
|
1679 |
+
if type == socket.SOCK_STREAM:
|
1680 |
+
sock.listen(5)
|
1681 |
+
return sock
|
1682 |
+
except Exception:
|
1683 |
+
sock.close()
|
1684 |
+
raise
|
1685 |
+
|
1686 |
+
|
1687 |
+
def bind_unix_socket(name, type=socket.SOCK_STREAM):
|
1688 |
+
"""Bind a UNIX socket."""
|
1689 |
+
assert psutil.POSIX
|
1690 |
+
assert not os.path.exists(name), name
|
1691 |
+
sock = socket.socket(socket.AF_UNIX, type)
|
1692 |
+
try:
|
1693 |
+
sock.bind(name)
|
1694 |
+
if type == socket.SOCK_STREAM:
|
1695 |
+
sock.listen(5)
|
1696 |
+
except Exception:
|
1697 |
+
sock.close()
|
1698 |
+
raise
|
1699 |
+
return sock
|
1700 |
+
|
1701 |
+
|
1702 |
+
def tcp_socketpair(family, addr=("", 0)):
|
1703 |
+
"""Build a pair of TCP sockets connected to each other.
|
1704 |
+
Return a (server, client) tuple.
|
1705 |
+
"""
|
1706 |
+
with contextlib.closing(socket.socket(family, SOCK_STREAM)) as ll:
|
1707 |
+
ll.bind(addr)
|
1708 |
+
ll.listen(5)
|
1709 |
+
addr = ll.getsockname()
|
1710 |
+
c = socket.socket(family, SOCK_STREAM)
|
1711 |
+
try:
|
1712 |
+
c.connect(addr)
|
1713 |
+
caddr = c.getsockname()
|
1714 |
+
while True:
|
1715 |
+
a, addr = ll.accept()
|
1716 |
+
# check that we've got the correct client
|
1717 |
+
if addr == caddr:
|
1718 |
+
return (a, c)
|
1719 |
+
a.close()
|
1720 |
+
except OSError:
|
1721 |
+
c.close()
|
1722 |
+
raise
|
1723 |
+
|
1724 |
+
|
1725 |
+
def unix_socketpair(name):
|
1726 |
+
"""Build a pair of UNIX sockets connected to each other through
|
1727 |
+
the same UNIX file name.
|
1728 |
+
Return a (server, client) tuple.
|
1729 |
+
"""
|
1730 |
+
assert psutil.POSIX
|
1731 |
+
server = client = None
|
1732 |
+
try:
|
1733 |
+
server = bind_unix_socket(name, type=socket.SOCK_STREAM)
|
1734 |
+
server.setblocking(0)
|
1735 |
+
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
1736 |
+
client.setblocking(0)
|
1737 |
+
client.connect(name)
|
1738 |
+
# new = server.accept()
|
1739 |
+
except Exception:
|
1740 |
+
if server is not None:
|
1741 |
+
server.close()
|
1742 |
+
if client is not None:
|
1743 |
+
client.close()
|
1744 |
+
raise
|
1745 |
+
return (server, client)
|
1746 |
+
|
1747 |
+
|
1748 |
+
@contextlib.contextmanager
|
1749 |
+
def create_sockets():
|
1750 |
+
"""Open as many socket families / types as possible."""
|
1751 |
+
socks = []
|
1752 |
+
fname1 = fname2 = None
|
1753 |
+
try:
|
1754 |
+
socks.append(bind_socket(socket.AF_INET, socket.SOCK_STREAM))
|
1755 |
+
socks.append(bind_socket(socket.AF_INET, socket.SOCK_DGRAM))
|
1756 |
+
if supports_ipv6():
|
1757 |
+
socks.append(bind_socket(socket.AF_INET6, socket.SOCK_STREAM))
|
1758 |
+
socks.append(bind_socket(socket.AF_INET6, socket.SOCK_DGRAM))
|
1759 |
+
if POSIX and HAS_CONNECTIONS_UNIX:
|
1760 |
+
fname1 = get_testfn()
|
1761 |
+
fname2 = get_testfn()
|
1762 |
+
s1, s2 = unix_socketpair(fname1)
|
1763 |
+
s3 = bind_unix_socket(fname2, type=socket.SOCK_DGRAM)
|
1764 |
+
for s in (s1, s2, s3):
|
1765 |
+
socks.append(s)
|
1766 |
+
yield socks
|
1767 |
+
finally:
|
1768 |
+
for s in socks:
|
1769 |
+
s.close()
|
1770 |
+
for fname in (fname1, fname2):
|
1771 |
+
if fname is not None:
|
1772 |
+
safe_rmpath(fname)
|
1773 |
+
|
1774 |
+
|
1775 |
+
def check_net_address(addr, family):
|
1776 |
+
"""Check a net address validity. Supported families are IPv4,
|
1777 |
+
IPv6 and MAC addresses.
|
1778 |
+
"""
|
1779 |
+
import ipaddress # python >= 3.3 / requires "pip install ipaddress"
|
1780 |
+
|
1781 |
+
if enum and PY3 and not PYPY:
|
1782 |
+
assert isinstance(family, enum.IntEnum), family
|
1783 |
+
if family == socket.AF_INET:
|
1784 |
+
octs = [int(x) for x in addr.split('.')]
|
1785 |
+
assert len(octs) == 4, addr
|
1786 |
+
for num in octs:
|
1787 |
+
assert 0 <= num <= 255, addr
|
1788 |
+
if not PY3:
|
1789 |
+
addr = unicode(addr)
|
1790 |
+
ipaddress.IPv4Address(addr)
|
1791 |
+
elif family == socket.AF_INET6:
|
1792 |
+
assert isinstance(addr, str), addr
|
1793 |
+
if not PY3:
|
1794 |
+
addr = unicode(addr)
|
1795 |
+
ipaddress.IPv6Address(addr)
|
1796 |
+
elif family == psutil.AF_LINK:
|
1797 |
+
assert re.match(r'([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr
|
1798 |
+
else:
|
1799 |
+
raise ValueError("unknown family %r" % family)
|
1800 |
+
|
1801 |
+
|
1802 |
+
def check_connection_ntuple(conn):
|
1803 |
+
"""Check validity of a connection namedtuple."""
|
1804 |
+
|
1805 |
+
def check_ntuple(conn):
|
1806 |
+
has_pid = len(conn) == 7
|
1807 |
+
assert len(conn) in (6, 7), len(conn)
|
1808 |
+
assert conn[0] == conn.fd, conn.fd
|
1809 |
+
assert conn[1] == conn.family, conn.family
|
1810 |
+
assert conn[2] == conn.type, conn.type
|
1811 |
+
assert conn[3] == conn.laddr, conn.laddr
|
1812 |
+
assert conn[4] == conn.raddr, conn.raddr
|
1813 |
+
assert conn[5] == conn.status, conn.status
|
1814 |
+
if has_pid:
|
1815 |
+
assert conn[6] == conn.pid, conn.pid
|
1816 |
+
|
1817 |
+
def check_family(conn):
|
1818 |
+
assert conn.family in (AF_INET, AF_INET6, AF_UNIX), conn.family
|
1819 |
+
if enum is not None:
|
1820 |
+
assert isinstance(conn.family, enum.IntEnum), conn
|
1821 |
+
else:
|
1822 |
+
assert isinstance(conn.family, int), conn
|
1823 |
+
if conn.family == AF_INET:
|
1824 |
+
# actually try to bind the local socket; ignore IPv6
|
1825 |
+
# sockets as their address might be represented as
|
1826 |
+
# an IPv4-mapped-address (e.g. "::127.0.0.1")
|
1827 |
+
# and that's rejected by bind()
|
1828 |
+
s = socket.socket(conn.family, conn.type)
|
1829 |
+
with contextlib.closing(s):
|
1830 |
+
try:
|
1831 |
+
s.bind((conn.laddr[0], 0))
|
1832 |
+
except socket.error as err:
|
1833 |
+
if err.errno != errno.EADDRNOTAVAIL:
|
1834 |
+
raise
|
1835 |
+
elif conn.family == AF_UNIX:
|
1836 |
+
assert conn.status == psutil.CONN_NONE, conn.status
|
1837 |
+
|
1838 |
+
def check_type(conn):
|
1839 |
+
# SOCK_SEQPACKET may happen in case of AF_UNIX socks
|
1840 |
+
SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())
|
1841 |
+
assert conn.type in (
|
1842 |
+
socket.SOCK_STREAM,
|
1843 |
+
socket.SOCK_DGRAM,
|
1844 |
+
SOCK_SEQPACKET,
|
1845 |
+
), conn.type
|
1846 |
+
if enum is not None:
|
1847 |
+
assert isinstance(conn.type, enum.IntEnum), conn
|
1848 |
+
else:
|
1849 |
+
assert isinstance(conn.type, int), conn
|
1850 |
+
if conn.type == socket.SOCK_DGRAM:
|
1851 |
+
assert conn.status == psutil.CONN_NONE, conn.status
|
1852 |
+
|
1853 |
+
def check_addrs(conn):
|
1854 |
+
# check IP address and port sanity
|
1855 |
+
for addr in (conn.laddr, conn.raddr):
|
1856 |
+
if conn.family in (AF_INET, AF_INET6):
|
1857 |
+
assert isinstance(addr, tuple), type(addr)
|
1858 |
+
if not addr:
|
1859 |
+
continue
|
1860 |
+
assert isinstance(addr.port, int), type(addr.port)
|
1861 |
+
assert 0 <= addr.port <= 65535, addr.port
|
1862 |
+
check_net_address(addr.ip, conn.family)
|
1863 |
+
elif conn.family == AF_UNIX:
|
1864 |
+
assert isinstance(addr, str), type(addr)
|
1865 |
+
|
1866 |
+
def check_status(conn):
|
1867 |
+
assert isinstance(conn.status, str), conn.status
|
1868 |
+
valids = [
|
1869 |
+
getattr(psutil, x) for x in dir(psutil) if x.startswith('CONN_')
|
1870 |
+
]
|
1871 |
+
assert conn.status in valids, conn.status
|
1872 |
+
if conn.family in (AF_INET, AF_INET6) and conn.type == SOCK_STREAM:
|
1873 |
+
assert conn.status != psutil.CONN_NONE, conn.status
|
1874 |
+
else:
|
1875 |
+
assert conn.status == psutil.CONN_NONE, conn.status
|
1876 |
+
|
1877 |
+
check_ntuple(conn)
|
1878 |
+
check_family(conn)
|
1879 |
+
check_type(conn)
|
1880 |
+
check_addrs(conn)
|
1881 |
+
check_status(conn)
|
1882 |
+
|
1883 |
+
|
1884 |
+
def filter_proc_connections(cons):
|
1885 |
+
"""Our process may start with some open UNIX sockets which are not
|
1886 |
+
initialized by us, invalidating unit tests.
|
1887 |
+
"""
|
1888 |
+
new = []
|
1889 |
+
for conn in cons:
|
1890 |
+
if POSIX and conn.family == socket.AF_UNIX:
|
1891 |
+
if MACOS and "/syslog" in conn.raddr:
|
1892 |
+
debug("skipping %s" % str(conn))
|
1893 |
+
continue
|
1894 |
+
new.append(conn)
|
1895 |
+
return new
|
1896 |
+
|
1897 |
+
|
1898 |
+
# ===================================================================
|
1899 |
+
# --- compatibility
|
1900 |
+
# ===================================================================
|
1901 |
+
|
1902 |
+
|
1903 |
+
def reload_module(module):
|
1904 |
+
"""Backport of importlib.reload of Python 3.3+."""
|
1905 |
+
try:
|
1906 |
+
import importlib
|
1907 |
+
|
1908 |
+
if not hasattr(importlib, 'reload'): # python <=3.3
|
1909 |
+
raise ImportError
|
1910 |
+
except ImportError:
|
1911 |
+
import imp
|
1912 |
+
|
1913 |
+
return imp.reload(module)
|
1914 |
+
else:
|
1915 |
+
return importlib.reload(module)
|
1916 |
+
|
1917 |
+
|
1918 |
+
def import_module_by_path(path):
|
1919 |
+
name = os.path.splitext(os.path.basename(path))[0]
|
1920 |
+
if sys.version_info[0] < 3:
|
1921 |
+
import imp
|
1922 |
+
|
1923 |
+
return imp.load_source(name, path)
|
1924 |
+
else:
|
1925 |
+
import importlib.util
|
1926 |
+
|
1927 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
1928 |
+
mod = importlib.util.module_from_spec(spec)
|
1929 |
+
spec.loader.exec_module(mod)
|
1930 |
+
return mod
|
1931 |
+
|
1932 |
+
|
1933 |
+
# ===================================================================
|
1934 |
+
# --- others
|
1935 |
+
# ===================================================================
|
1936 |
+
|
1937 |
+
|
1938 |
+
def warn(msg):
|
1939 |
+
"""Raise a warning msg."""
|
1940 |
+
warnings.warn(msg, UserWarning, stacklevel=2)
|
1941 |
+
|
1942 |
+
|
1943 |
+
def is_namedtuple(x):
|
1944 |
+
"""Check if object is an instance of namedtuple."""
|
1945 |
+
t = type(x)
|
1946 |
+
b = t.__bases__
|
1947 |
+
if len(b) != 1 or b[0] != tuple:
|
1948 |
+
return False
|
1949 |
+
f = getattr(t, '_fields', None)
|
1950 |
+
if not isinstance(f, tuple):
|
1951 |
+
return False
|
1952 |
+
return all(isinstance(n, str) for n in f)
|
1953 |
+
|
1954 |
+
|
1955 |
+
if POSIX:
|
1956 |
+
|
1957 |
+
@contextlib.contextmanager
|
1958 |
+
def copyload_shared_lib(suffix=""):
|
1959 |
+
"""Ctx manager which picks up a random shared CO lib used
|
1960 |
+
by this process, copies it in another location and loads it
|
1961 |
+
in memory via ctypes. Return the new absolutized path.
|
1962 |
+
"""
|
1963 |
+
exe = 'pypy' if PYPY else 'python'
|
1964 |
+
ext = ".so"
|
1965 |
+
dst = get_testfn(suffix=suffix + ext)
|
1966 |
+
libs = [
|
1967 |
+
x.path
|
1968 |
+
for x in psutil.Process().memory_maps()
|
1969 |
+
if os.path.splitext(x.path)[1] == ext and exe in x.path.lower()
|
1970 |
+
]
|
1971 |
+
src = random.choice(libs)
|
1972 |
+
shutil.copyfile(src, dst)
|
1973 |
+
try:
|
1974 |
+
ctypes.CDLL(dst)
|
1975 |
+
yield dst
|
1976 |
+
finally:
|
1977 |
+
safe_rmpath(dst)
|
1978 |
+
|
1979 |
+
else:
|
1980 |
+
|
1981 |
+
@contextlib.contextmanager
|
1982 |
+
def copyload_shared_lib(suffix=""):
|
1983 |
+
"""Ctx manager which picks up a random shared DLL lib used
|
1984 |
+
by this process, copies it in another location and loads it
|
1985 |
+
in memory via ctypes.
|
1986 |
+
Return the new absolutized, normcased path.
|
1987 |
+
"""
|
1988 |
+
from ctypes import WinError
|
1989 |
+
from ctypes import wintypes
|
1990 |
+
|
1991 |
+
ext = ".dll"
|
1992 |
+
dst = get_testfn(suffix=suffix + ext)
|
1993 |
+
libs = [
|
1994 |
+
x.path
|
1995 |
+
for x in psutil.Process().memory_maps()
|
1996 |
+
if x.path.lower().endswith(ext)
|
1997 |
+
and 'python' in os.path.basename(x.path).lower()
|
1998 |
+
and 'wow64' not in x.path.lower()
|
1999 |
+
]
|
2000 |
+
if PYPY and not libs:
|
2001 |
+
libs = [
|
2002 |
+
x.path
|
2003 |
+
for x in psutil.Process().memory_maps()
|
2004 |
+
if 'pypy' in os.path.basename(x.path).lower()
|
2005 |
+
]
|
2006 |
+
src = random.choice(libs)
|
2007 |
+
shutil.copyfile(src, dst)
|
2008 |
+
cfile = None
|
2009 |
+
try:
|
2010 |
+
cfile = ctypes.WinDLL(dst)
|
2011 |
+
yield dst
|
2012 |
+
finally:
|
2013 |
+
# Work around OverflowError:
|
2014 |
+
# - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
|
2015 |
+
# job/o53330pbnri9bcw7
|
2016 |
+
# - http://bugs.python.org/issue30286
|
2017 |
+
# - http://stackoverflow.com/questions/23522055
|
2018 |
+
if cfile is not None:
|
2019 |
+
FreeLibrary = ctypes.windll.kernel32.FreeLibrary
|
2020 |
+
FreeLibrary.argtypes = [wintypes.HMODULE]
|
2021 |
+
ret = FreeLibrary(cfile._handle)
|
2022 |
+
if ret == 0:
|
2023 |
+
WinError()
|
2024 |
+
safe_rmpath(dst)
|
2025 |
+
|
2026 |
+
|
2027 |
+
# ===================================================================
|
2028 |
+
# --- Exit funs (first is executed last)
|
2029 |
+
# ===================================================================
|
2030 |
+
|
2031 |
+
|
2032 |
+
# this is executed first
|
2033 |
+
@atexit.register
|
2034 |
+
def cleanup_test_procs():
|
2035 |
+
reap_children(recursive=True)
|
2036 |
+
|
2037 |
+
|
2038 |
+
# atexit module does not execute exit functions in case of SIGTERM, which
|
2039 |
+
# gets sent to test subprocesses, which is a problem if they import this
|
2040 |
+
# module. With this it will. See:
|
2041 |
+
# https://gmpy.dev/blog/2016/how-to-always-execute-exit-functions-in-python
|
2042 |
+
if POSIX:
|
2043 |
+
signal.signal(signal.SIGTERM, lambda sig, _: sys.exit(sig))
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__main__.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
3 |
+
# found in the LICENSE file.
|
4 |
+
|
5 |
+
"""Run unit tests. This is invoked by:
|
6 |
+
$ python -m psutil.tests.
|
7 |
+
"""
|
8 |
+
|
9 |
+
from .runner import main
|
10 |
+
|
11 |
+
|
12 |
+
main()
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/runner.cpython-310.pyc
ADDED
Binary file (11.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_bsd.cpython-310.pyc
ADDED
Binary file (19.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_connections.cpython-310.pyc
ADDED
Binary file (15.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_contracts.cpython-310.pyc
ADDED
Binary file (13.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_linux.cpython-310.pyc
ADDED
Binary file (73.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_memleaks.cpython-310.pyc
ADDED
Binary file (22.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_osx.cpython-310.pyc
ADDED
Binary file (6.59 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_posix.cpython-310.pyc
ADDED
Binary file (13.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process.cpython-310.pyc
ADDED
Binary file (49.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process_all.cpython-310.pyc
ADDED
Binary file (14.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/psutil/tests/__pycache__/test_system.cpython-310.pyc
ADDED
Binary file (28.7 kB). View file
|
|