repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
psutil | psutil-master/CONTRIBUTING.md | Contributing to psutil project
==============================
Issues
------
* The issue tracker is for reporting problems or proposing enhancements related
to the **program code**.
* Please do not open issues **asking for support**. Instead, use the forum at:
https://groups.google.com/g/psutil.
* Before submitting a new issue, **search** if there are existing issues for
the same topic.
* **Be clear** in describing what the problem is and try to be accurate in
editing the default issue **template**. There is a bot which automatically
assigns **labels** based on issue's title and body format. Labels help
keeping the issues properly organized and searchable (by OS, issue type, etc.).
* When reporting a malfunction, consider enabling
[debug mode](https://psutil.readthedocs.io/en/latest/#debug-mode) first.
* To report a **security vulnerability**, use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and the disclosure of the reported problem.
Pull Requests
-------------
* The PR system is for fixing bugs or make enhancements related to the
**program code**.
* If you wish to implement a new feature or add support for a new platform it's
better to **discuss it first**, either on the issue tracker, the forum or via
private email.
* In order to get acquainted with the code base and tooling, take a look at the
**[Development Guide](https://github.com/giampaolo/psutil/blob/master/docs/DEVGUIDE.rst)**.
* If you can, remember to update
[HISTORY.rst](https://github.com/giampaolo/psutil/blob/master/HISTORY.rst)
and [CREDITS](https://github.com/giampaolo/psutil/blob/master/CREDITS) file.
| 1,681 | 45.722222 | 93 | md |
psutil | psutil-master/appveyor.yml | # Build: 3 (bump this up by 1 to force an appveyor run)
os: Visual Studio 2015
# avoid 2 builds when pushing on PRs
skip_branch_with_pr: true
# avoid build on new GIT tag
skip_tags: true
matrix:
# stop build on first failure
fast_finish: true
environment:
global:
# SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the
# /E:ON and /V:ON options are not enabled in the batch script interpreter
# See: http://stackoverflow.com/a/13751649/163740
WITH_COMPILER: "cmd /E:ON /V:ON /C .\\scripts\\internal\\appveyor_run_with_compiler.cmd"
PYTHONWARNINGS: always
PYTHONUNBUFFERED: 1
PSUTIL_DEBUG: 1
matrix:
# 32 bits
- PYTHON: "C:\\Python27"
PYTHON_VERSION: "2.7.x"
PYTHON_ARCH: "32"
# 64 bits
- PYTHON: "C:\\Python27-x64"
PYTHON_VERSION: "2.7.x"
PYTHON_ARCH: "64"
init:
- "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%"
install:
- "%WITH_COMPILER% %PYTHON%/python.exe -m pip --version"
- "%WITH_COMPILER% %PYTHON%/python.exe -m pip install --upgrade --user setuptools pip"
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py setup-dev-env"
- "%WITH_COMPILER% %PYTHON%/python.exe -m pip freeze"
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py install"
build: off
test_script:
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py test"
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py test-memleaks"
after_test:
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py wheel"
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/print_hashes.py dist"
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/print_access_denied.py"
- "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/print_api_speed.py"
artifacts:
- path: dist\*
cache:
- '%LOCALAPPDATA%\pip\Cache'
# on_success:
# - might want to upload the content of dist/*.whl to a public wheelhouse
skip_commits:
message: skip-appveyor
# run build only if one of the following files is modified on commit
only_commits:
files:
- .ci/appveyor/*
- appveyor.yml
- psutil/__init__.py
- psutil/_common.py
- psutil/_compat.py
- psutil/_psutil_common.*
- psutil/_psutil_windows.*
- psutil/_pswindows.py
- psutil/arch/windows/*
- psutil/tests/*
- scripts/*
- scripts/internal/*
- setup.py
| 2,395 | 27.52381 | 92 | yml |
psutil | psutil-master/setup.py | #!/usr/bin/env python3
# Copyright (c) 2009 Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Cross-platform lib for process and system monitoring in Python."""
from __future__ import print_function
import contextlib
import glob
import io
import os
import platform
import re
import shutil
import struct
import subprocess
import sys
import tempfile
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
import setuptools
from setuptools import Extension
from setuptools import setup
except ImportError:
setuptools = None
from distutils.core import Extension
from distutils.core import setup
try:
from wheel.bdist_wheel import bdist_wheel
except ImportError:
if "CIBUILDWHEEL" in os.environ:
raise
bdist_wheel = None
HERE = os.path.abspath(os.path.dirname(__file__))
# ...so we can import _common.py and _compat.py
sys.path.insert(0, os.path.join(HERE, "psutil"))
from _common import AIX # NOQA
from _common import BSD # NOQA
from _common import FREEBSD # NOQA
from _common import LINUX # NOQA
from _common import MACOS # NOQA
from _common import NETBSD # NOQA
from _common import OPENBSD # NOQA
from _common import POSIX # NOQA
from _common import SUNOS # NOQA
from _common import WINDOWS # NOQA
from _common import hilite # NOQA
from _compat import PY3 # NOQA
from _compat import which # NOQA
PYPY = '__pypy__' in sys.builtin_module_names
PY36_PLUS = sys.version_info[:2] >= (3, 6)
PY37_PLUS = sys.version_info[:2] >= (3, 7)
CP36_PLUS = PY36_PLUS and sys.implementation.name == "cpython"
CP37_PLUS = PY37_PLUS and sys.implementation.name == "cpython"
macros = []
if POSIX:
macros.append(("PSUTIL_POSIX", 1))
if BSD:
macros.append(("PSUTIL_BSD", 1))
# Needed to determine _Py_PARSE_PID in case it's missing (Python 2, PyPy).
# Taken from Lib/test/test_fcntl.py.
# XXX: not bullet proof as the (long long) case is missing.
if struct.calcsize('l') <= 8:
macros.append(('PSUTIL_SIZEOF_PID_T', '4')) # int
else:
macros.append(('PSUTIL_SIZEOF_PID_T', '8')) # long
sources = ['psutil/_psutil_common.c']
if POSIX:
sources.append('psutil/_psutil_posix.c')
extras_require = {"test": [
"enum34; python_version <= '3.4'",
"ipaddress; python_version < '3.0'",
"mock; python_version < '3.0'",
]}
if not PYPY:
extras_require['test'].extend([
"pywin32; sys.platform == 'win32'",
"wmi; sys.platform == 'win32'"])
def get_version():
INIT = os.path.join(HERE, 'psutil/__init__.py')
with open(INIT, 'r') as f:
for line in f:
if line.startswith('__version__'):
ret = eval(line.strip().split(' = ')[1])
assert ret.count('.') == 2, ret
for num in ret.split('.'):
assert num.isdigit(), ret
return ret
raise ValueError("couldn't find version string")
VERSION = get_version()
macros.append(('PSUTIL_VERSION', int(VERSION.replace('.', ''))))
# Py_LIMITED_API lets us create a single wheel which works with multiple
# python versions, including unreleased ones.
if bdist_wheel and CP36_PLUS and (MACOS or LINUX):
py_limited_api = {"py_limited_api": True}
macros.append(('Py_LIMITED_API', '0x03060000'))
elif bdist_wheel and CP37_PLUS and WINDOWS:
# PyErr_SetFromWindowsErr / PyErr_SetFromWindowsErrWithFilename are
# part of the stable API/ABI starting with CPython 3.7
py_limited_api = {"py_limited_api": True}
macros.append(('Py_LIMITED_API', '0x03070000'))
else:
py_limited_api = {}
def get_long_description():
script = os.path.join(HERE, "scripts", "internal", "convert_readme.py")
readme = os.path.join(HERE, 'README.rst')
p = subprocess.Popen([sys.executable, script, readme],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise RuntimeError(stderr)
return stdout
@contextlib.contextmanager
def silenced_output(stream_name):
class DummyFile(io.BytesIO):
# see: https://github.com/giampaolo/psutil/issues/678
errors = "ignore"
def write(self, s):
pass
orig = getattr(sys, stream_name)
try:
setattr(sys, stream_name, DummyFile())
yield
finally:
setattr(sys, stream_name, orig)
def missdeps(cmdline):
s = "psutil could not be installed from sources"
if not SUNOS and not which("gcc"):
s += " because gcc is not installed. "
else:
s += ". Perhaps Python header files are not installed. "
s += "Try running:\n"
s += " %s" % cmdline
print(hilite(s, color="red", bold=True), file=sys.stderr)
def unix_can_compile(c_code):
from distutils.errors import CompileError
from distutils.unixccompiler import UnixCCompiler
with tempfile.NamedTemporaryFile(
suffix='.c', delete=False, mode="wt") as f:
f.write(c_code)
tempdir = tempfile.mkdtemp()
try:
compiler = UnixCCompiler()
# https://github.com/giampaolo/psutil/pull/1568
if os.getenv('CC'):
compiler.set_executable('compiler_so', os.getenv('CC'))
with silenced_output('stderr'):
with silenced_output('stdout'):
compiler.compile([f.name], output_dir=tempdir)
except CompileError:
return False
else:
return True
finally:
os.remove(f.name)
shutil.rmtree(tempdir)
if WINDOWS:
def get_winver():
maj, min = sys.getwindowsversion()[0:2]
return '0x0%s' % ((maj * 100) + min)
if sys.getwindowsversion()[0] < 6:
msg = "this Windows version is too old (< Windows Vista); "
msg += "psutil 3.4.2 is the latest version which supports Windows "
msg += "2000, XP and 2003 server"
raise RuntimeError(msg)
macros.append(("PSUTIL_WINDOWS", 1))
macros.extend([
# be nice to mingw, see:
# http://www.mingw.org/wiki/Use_more_recent_defined_functions
('_WIN32_WINNT', get_winver()),
('_AVAIL_WINVER_', get_winver()),
('_CRT_SECURE_NO_WARNINGS', None),
# see: https://github.com/giampaolo/psutil/issues/348
('PSAPI_VERSION', 1),
])
ext = Extension(
'psutil._psutil_windows',
sources=(
sources +
["psutil/_psutil_windows.c"] +
glob.glob("psutil/arch/windows/*.c")
),
define_macros=macros,
libraries=[
"psapi", "kernel32", "advapi32", "shell32", "netapi32",
"ws2_32", "PowrProf", "pdh",
],
# extra_compile_args=["/W 4"],
# extra_link_args=["/DEBUG"],
**py_limited_api
)
elif MACOS:
macros.append(("PSUTIL_OSX", 1))
ext = Extension(
'psutil._psutil_osx',
sources=(
sources +
["psutil/_psutil_osx.c"] +
glob.glob("psutil/arch/osx/*.c")
),
define_macros=macros,
extra_link_args=[
'-framework', 'CoreFoundation', '-framework', 'IOKit'
],
**py_limited_api)
elif FREEBSD:
macros.append(("PSUTIL_FREEBSD", 1))
ext = Extension(
'psutil._psutil_bsd',
sources=(
sources +
["psutil/_psutil_bsd.c"] +
glob.glob("psutil/arch/bsd/*.c") +
glob.glob("psutil/arch/freebsd/*.c")
),
define_macros=macros,
libraries=["devstat"],
**py_limited_api)
elif OPENBSD:
macros.append(("PSUTIL_OPENBSD", 1))
ext = Extension(
'psutil._psutil_bsd',
sources=(
sources +
["psutil/_psutil_bsd.c"] +
glob.glob("psutil/arch/bsd/*.c") +
glob.glob("psutil/arch/openbsd/*.c")
),
define_macros=macros,
libraries=["kvm"],
**py_limited_api)
elif NETBSD:
macros.append(("PSUTIL_NETBSD", 1))
ext = Extension(
'psutil._psutil_bsd',
sources=(
sources +
["psutil/_psutil_bsd.c"] +
glob.glob("psutil/arch/bsd/*.c") +
glob.glob("psutil/arch/netbsd/*.c")
),
define_macros=macros,
libraries=["kvm"],
**py_limited_api)
elif LINUX:
# see: https://github.com/giampaolo/psutil/issues/659
if not unix_can_compile("#include <linux/ethtool.h>"):
macros.append(("PSUTIL_ETHTOOL_MISSING_TYPES", 1))
macros.append(("PSUTIL_LINUX", 1))
ext = Extension(
'psutil._psutil_linux',
sources=sources + ['psutil/_psutil_linux.c'],
define_macros=macros,
**py_limited_api)
elif SUNOS:
macros.append(("PSUTIL_SUNOS", 1))
ext = Extension(
'psutil._psutil_sunos',
sources=sources + [
'psutil/_psutil_sunos.c',
'psutil/arch/solaris/v10/ifaddrs.c',
'psutil/arch/solaris/environ.c'
],
define_macros=macros,
libraries=['kstat', 'nsl', 'socket'],
**py_limited_api)
elif AIX:
macros.append(("PSUTIL_AIX", 1))
ext = Extension(
'psutil._psutil_aix',
sources=sources + [
'psutil/_psutil_aix.c',
'psutil/arch/aix/net_connections.c',
'psutil/arch/aix/common.c',
'psutil/arch/aix/ifaddrs.c'],
libraries=['perfstat'],
define_macros=macros,
**py_limited_api)
else:
sys.exit('platform %s is not supported' % sys.platform)
if POSIX:
posix_extension = Extension(
'psutil._psutil_posix',
define_macros=macros,
sources=sources,
**py_limited_api)
if SUNOS:
def get_sunos_update():
# See https://serverfault.com/q/524883
# for an explanation of Solaris /etc/release
with open('/etc/release') as f:
update = re.search(r'(?<=s10s_u)[0-9]{1,2}', f.readline())
return int(update.group(0)) if update else 0
posix_extension.libraries.append('socket')
if platform.release() == '5.10':
# Detect Solaris 5.10, update >= 4, see:
# https://github.com/giampaolo/psutil/pull/1638
if get_sunos_update() >= 4:
# MIB compliance starts with SunOS 5.10 Update 4:
posix_extension.define_macros.append(('NEW_MIB_COMPLIANT', 1))
posix_extension.sources.append('psutil/arch/solaris/v10/ifaddrs.c')
posix_extension.define_macros.append(('PSUTIL_SUNOS10', 1))
else:
# Other releases are by default considered to be new mib compliant.
posix_extension.define_macros.append(('NEW_MIB_COMPLIANT', 1))
elif AIX:
posix_extension.sources.append('psutil/arch/aix/ifaddrs.c')
extensions = [ext, posix_extension]
else:
extensions = [ext]
cmdclass = {}
if py_limited_api:
class bdist_wheel_abi3(bdist_wheel):
def get_tag(self):
python, abi, plat = bdist_wheel.get_tag(self)
return python, "abi3", plat
cmdclass["bdist_wheel"] = bdist_wheel_abi3
def main():
kwargs = dict(
name='psutil',
version=VERSION,
cmdclass=cmdclass,
description=__doc__ .replace('\n', ' ').strip() if __doc__ else '',
long_description=get_long_description(),
long_description_content_type='text/x-rst',
keywords=[
'ps', 'top', 'kill', 'free', 'lsof', 'netstat', 'nice', 'tty',
'ionice', 'uptime', 'taskmgr', 'process', 'df', 'iotop', 'iostat',
'ifconfig', 'taskset', 'who', 'pidof', 'pmap', 'smem', 'pstree',
'monitoring', 'ulimit', 'prlimit', 'smem', 'performance',
'metrics', 'agent', 'observability',
],
author='Giampaolo Rodola',
author_email='[email protected]',
url='https://github.com/giampaolo/psutil',
platforms='Platform Independent',
license='BSD-3-Clause',
packages=['psutil', 'psutil.tests'],
ext_modules=extensions,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows :: Windows 10',
'Operating System :: Microsoft :: Windows :: Windows 7',
'Operating System :: Microsoft :: Windows :: Windows 8',
'Operating System :: Microsoft :: Windows :: Windows 8.1',
'Operating System :: Microsoft :: Windows :: Windows Server 2003',
'Operating System :: Microsoft :: Windows :: Windows Server 2008',
'Operating System :: Microsoft :: Windows :: Windows Vista',
'Operating System :: Microsoft',
'Operating System :: OS Independent',
'Operating System :: POSIX :: AIX',
'Operating System :: POSIX :: BSD :: FreeBSD',
'Operating System :: POSIX :: BSD :: NetBSD',
'Operating System :: POSIX :: BSD :: OpenBSD',
'Operating System :: POSIX :: BSD',
'Operating System :: POSIX :: Linux',
'Operating System :: POSIX :: SunOS/Solaris',
'Operating System :: POSIX',
'Programming Language :: C',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Benchmark',
'Topic :: System :: Hardware :: Hardware Drivers',
'Topic :: System :: Hardware',
'Topic :: System :: Monitoring',
'Topic :: System :: Networking :: Monitoring :: Hardware Watchdog',
'Topic :: System :: Networking :: Monitoring',
'Topic :: System :: Networking',
'Topic :: System :: Operating System',
'Topic :: System :: Systems Administration',
'Topic :: Utilities',
],
)
if setuptools is not None:
kwargs.update(
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
extras_require=extras_require,
zip_safe=False,
)
success = False
try:
setup(**kwargs)
success = True
finally:
cmd = sys.argv[1] if len(sys.argv) >= 2 else ''
if not success and POSIX and \
cmd.startswith(("build", "install", "sdist", "bdist",
"develop")):
py3 = "3" if PY3 else ""
if LINUX:
pyimpl = "pypy" if PYPY else "python"
if which('dpkg'):
missdeps("sudo apt-get install gcc %s%s-dev" %
(pyimpl, py3))
elif which('rpm'):
missdeps("sudo yum install gcc %s%s-devel" % (pyimpl, py3))
elif which('apk'):
missdeps("sudo apk add gcc %s%s-dev" % (pyimpl, py3))
elif MACOS:
print(hilite("XCode (https://developer.apple.com/xcode/) "
"is not installed", color="red"), file=sys.stderr)
elif FREEBSD:
if which('pkg'):
missdeps("pkg install gcc python%s" % py3)
elif which('mport'): # MidnightBSD
missdeps("mport install gcc python%s" % py3)
elif OPENBSD:
missdeps("pkg_add -v gcc python%s" % py3)
elif NETBSD:
missdeps("pkgin install gcc python%s" % py3)
elif SUNOS:
missdeps("sudo ln -s /usr/bin/gcc /usr/local/bin/cc && "
"pkg install gcc")
if __name__ == '__main__':
main()
| 16,521 | 32.787321 | 79 | py |
psutil | psutil-master/.github/FUNDING.yml | # These are supported funding model platforms
tidelift: "pypi/psutil"
github: giampaolo
patreon: # Replace with a single Patreon username
open_collective: psutil
ko_fi: # Replace with a single Ko-fi username
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
custom: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=A9ZS7PKKRM3S8
| 392 | 38.3 | 91 | yml |
psutil | psutil-master/.github/PULL_REQUEST_TEMPLATE.md | ## Summary
* OS: { type-or-version }
* Bug fix: { yes/no }
* Type: { core, doc, performance, scripts, tests, wheels, new-api }
* Fixes: { comma-separated list of issues fixed by this PR, if any }
## Description
{{{
A clear explanation of your bugfix or enhancement. Please read the contributing guidelines before submit:
https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md
}}}
| 396 | 27.357143 | 107 | md |
psutil | psutil-master/.github/no-response.yml | # Configuration for probot-no-response: https://github.com/probot/no-response
# Number of days of inactivity before an issue is closed for lack of response
daysUntilClose: 14
# Label requiring a response
responseRequiredLabel: need-more-info
# Comment to post when closing an Issue for lack of response.
# Set to `false` to disable
closeComment: >
This issue has been automatically closed because there has been no response for more information from the original author. Please reach out if you have or find the answers requested so that this can be investigated further.
| 575 | 51.363636 | 225 | yml |
psutil | psutil-master/.github/ISSUE_TEMPLATE/bug.md | ---
name: Bug
about: Report a bug
title: "[OS] title"
labels: 'bug'
---
## Summary
* OS: { type-or-version }
* Architecture: { 64bit, 32bit, ARM, PowerPC, s390 }
* Psutil version: { pip3 show psutil }
* Python version: { python3 -V }
* Type: { core, doc, performance, scripts, tests, wheels, new-api, installation }
## Description
{{{
A clear explanation of the bug, including traceback message (if any). Please read the contributing guidelines before submit:
https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md
}}}
| 536 | 23.409091 | 126 | md |
psutil | psutil-master/.github/ISSUE_TEMPLATE/config.yml | blank_issues_enabled: false
contact_links:
- name: Ask a question
url: https://groups.google.com/g/psutil
about: Use this to ask for support
| 151 | 24.333333 | 43 | yml |
psutil | psutil-master/.github/ISSUE_TEMPLATE/enhancement.md | ---
name: Enhancement
about: Propose an enhancement
labels: 'enhancement'
title: "[OS] title"
---
## Summary
* OS: { type-or-version }
* Type: { core, doc, performance, scripts, tests, wheels, new-api }
## Description
{{{
A clear explanation of your proposal. Please read the contributing guidelines before submit:
https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md
}}}
| 392 | 18.65 | 94 | md |
psutil | psutil-master/.github/workflows/bsd.yml | # Execute tests on *BSD platforms. Does not produce wheels.
# Useful URLs:
# https://github.com/vmactions/freebsd-vm
# https://github.com/vmactions/openbsd-vm
# https://github.com/vmactions/netbsd-vm
on: [push, pull_request]
name: bsd-tests
concurrency:
group: ${{ github.ref }}-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.sha || '' }}
cancel-in-progress: true
jobs:
freebsd:
runs-on: macos-12
steps:
- uses: actions/checkout@v3
- name: Run tests
uses: vmactions/freebsd-vm@v0
with:
usesh: true
prepare: |
pkg install -y gcc python3
run: |
set -e -x
make install-pip
python3 -m pip install --user setuptools
make install
make test
make test-memleaks
openbsd:
runs-on: macos-12
steps:
- uses: actions/checkout@v3
- name: Run tests
uses: vmactions/openbsd-vm@v0
with:
usesh: true
prepare: |
set -e
pkg_add gcc python3
run: |
set -e
make install-pip
python3 -m pip install --user setuptools
make install
make test
make test-memleaks
netbsd:
runs-on: macos-12
steps:
- uses: actions/checkout@v3
- name: Run tests
uses: vmactions/netbsd-vm@v0
with:
usesh: true
prepare: |
set -e
pkg_add -v pkgin
pkgin update
pkgin -y install python311-* py311-setuptools-* gcc12-*
run: |
set -e
make install-pip PYTHON=python3.11
python3.11 -m pip install --user setuptools
make install PYTHON=python3.11
make test PYTHON=python3.11
make test-memleaks PYTHON=python3.11
| 1,955 | 27.764706 | 180 | yml |
psutil | psutil-master/.github/workflows/build.yml | # Runs CI tests and generates wheels on the following platforms:
#
# * Linux (py2 and py3)
# * macOS (py2 and py3)
# * Windows (py3, py2 is done by appveyor)
#
# Useful URLs:
# * https://github.com/pypa/cibuildwheel
# * https://github.com/actions/checkout
# * https://github.com/actions/setup-python
# * https://github.com/actions/upload-artifact
# * https://github.com/marketplace/actions/cancel-workflow-action
on: [push, pull_request]
name: build
jobs:
# Linux + macOS + Windows Python 3
py3:
name: py3-${{ matrix.os }}-${{ startsWith(matrix.os, 'windows') && matrix.archs || 'all' }}
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
archs: "x86_64 i686"
- os: macos-12
archs: "x86_64 arm64"
- os: windows-2019
archs: "AMD64"
- os: windows-2019
archs: "x86"
steps:
- name: Cancel previous runs
uses: styfle/[email protected]
with:
access_token: ${{ github.token }}
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.11
- name: Create wheels + run tests
uses: pypa/[email protected]
env:
CIBW_ARCHS: "${{ matrix.archs }}"
- name: Upload wheels
uses: actions/upload-artifact@v3
with:
name: wheels
path: wheelhouse
- name: Generate .tar.gz
if: matrix.os == 'ubuntu-latest'
run: |
make generate-manifest
python setup.py sdist
mv dist/psutil*.tar.gz wheelhouse/
# Linux + macOS + Python 2
py2:
name: py2-${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-12]
env:
CIBW_TEST_COMMAND:
PYTHONWARNINGS=always PYTHONUNBUFFERED=1 PSUTIL_DEBUG=1 python {project}/psutil/tests/runner.py &&
PYTHONWARNINGS=always PYTHONUNBUFFERED=1 PSUTIL_DEBUG=1 python {project}/psutil/tests/test_memleaks.py
CIBW_TEST_EXTRAS: test
CIBW_BUILD: 'cp27-*'
steps:
- name: Cancel previous runs
uses: styfle/[email protected]
with:
access_token: ${{ github.token }}
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.9
- name: Create wheels + run tests
uses: pypa/[email protected]
- name: Upload wheels
uses: actions/upload-artifact@v3
with:
name: wheels
path: wheelhouse
- name: Generate .tar.gz
if: matrix.os == 'ubuntu-latest'
run: |
make generate-manifest
python setup.py sdist
mv dist/psutil*.tar.gz wheelhouse/
# Run linters
linters:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
- name: 'Run linters'
run: |
# py3
python3 -m pip install flake8 isort
python3 -m flake8 .
python3 -m isort .
# clinter
find . -type f \( -iname "*.c" -o -iname "*.h" \) | xargs python3 scripts/internal/clinter.py
# Check sanity of .tar.gz + wheel files
check-dist:
needs: [py2, py3]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.x
- uses: actions/download-artifact@v3
with:
name: wheels
path: wheelhouse
- run: |
python scripts/internal/print_hashes.py wheelhouse/
pipx run twine check --strict wheelhouse/*
pipx run abi3audit --verbose --strict wheelhouse/*-abi3-*.whl
| 3,742 | 25.928058 | 110 | yml |
psutil | psutil-master/.github/workflows/issues.py | #!/usr/bin/env python3
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Bot triggered by Github Actions every time a new issue, PR or comment
is created. Assign labels, provide replies, closes issues, etc. depending
on the situation.
"""
from __future__ import print_function
import functools
import json
import os
import re
from pprint import pprint as pp
from github import Github
ROOT_DIR = os.path.realpath(
os.path.join(os.path.dirname(__file__), '..', '..'))
SCRIPTS_DIR = os.path.join(ROOT_DIR, 'scripts')
# --- constants
LABELS_MAP = {
# platforms
"linux": [
"linux", "ubuntu", "redhat", "mint", "centos", "red hat", "archlinux",
"debian", "alpine", "gentoo", "fedora", "slackware", "suse", "RHEL",
"opensuse", "manylinux", "apt ", "apt-", "rpm", "yum", "kali",
"/sys/class", "/proc/net", "/proc/disk", "/proc/smaps",
"/proc/vmstat",
],
"windows": [
"windows", "win32", "WinError", "WindowsError", "win10", "win7",
"win ", "mingw", "msys", "studio", "microsoft", "make.bat",
"CloseHandle", "GetLastError", "NtQuery", "DLL", "MSVC", "TCHAR",
"WCHAR", ".bat", "OpenProcess", "TerminateProcess", "appveyor",
"windows error", "NtWow64", "NTSTATUS", "Visual Studio",
],
"macos": [
"macos", "mac ", "osx", "os x", "mojave", "sierra", "capitan",
"yosemite", "catalina", "mojave", "big sur", "xcode", "darwin",
"dylib", "m1",
],
"aix": ["aix"],
"cygwin": ["cygwin"],
"freebsd": ["freebsd"],
"netbsd": ["netbsd"],
"openbsd": ["openbsd"],
"sunos": ["sunos", "solaris"],
"wsl": ["wsl"],
"unix": [
"psposix", "_psutil_posix", "waitpid", "statvfs", "/dev/tty",
"/dev/pts", "posix",
],
"pypy": ["pypy"],
# types
"enhancement": ["enhancement"],
"memleak": ["memory leak", "leaks memory", "memleak", "mem leak"],
"api": ["idea", "proposal", "api", "feature"],
"performance": ["performance", "speedup", "speed up", "slow", "fast"],
"wheels": ["wheel", "wheels"],
"scripts": [
"example script", "examples script", "example dir", "scripts/",
],
# bug
"bug": [
"fail", "can't execute", "can't install", "cannot execute",
"cannot install", "install error", "crash", "critical",
],
# doc
"doc": [
"doc ", "document ", "documentation", "readthedocs", "pythonhosted",
"HISTORY", "README", "dev guide", "devguide", "sphinx", "docfix",
"index.rst",
],
# tests
"tests": [
" test ", "tests", "travis", "coverage", "cirrus", "appveyor",
"continuous integration", "unittest", "pytest", "unit test",
],
# critical errors
"priority-high": [
"WinError", "WindowsError", "RuntimeError", "ZeroDivisionError",
"SystemError", "MemoryError", "core dumped",
"segfault", "segmentation fault",
],
}
LABELS_MAP['scripts'].extend(
[x for x in os.listdir(SCRIPTS_DIR) if x.endswith('.py')])
OS_LABELS = [
"linux", "windows", "macos", "freebsd", "openbsd", "netbsd", "openbsd",
"bsd", "sunos", "unix", "wsl", "aix", "cygwin",
]
ILLOGICAL_PAIRS = [
('bug', 'enhancement'),
('doc', 'tests'),
('scripts', 'doc'),
('scripts', 'tests'),
('bsd', 'freebsd'),
('bsd', 'openbsd'),
('bsd', 'netbsd'),
]
# --- replies
REPLY_MISSING_PYTHON_HEADERS = """\
It looks like you're missing `Python.h` headers. This usually means you have \
to install them first, then retry psutil installation.
Please read \
[INSTALL](https://github.com/giampaolo/psutil/blob/master/INSTALL.rst) \
instructions for your platform. \
This is an auto-generated response based on the text you submitted. \
If this was a mistake or you think there's a bug with psutil installation \
process, please add a comment to reopen this issue.
"""
# REPLY_UPDATE_CHANGELOG = """\
# """
# --- github API utils
def is_pr(issue):
return issue.pull_request is not None
def has_label(issue, label):
assigned = [x.name for x in issue.labels]
return label in assigned
def has_os_label(issue):
labels = set([x.name for x in issue.labels])
for label in OS_LABELS:
if label in labels:
return True
return False
def get_repo():
repo = os.environ['GITHUB_REPOSITORY']
token = os.environ['GITHUB_TOKEN']
return Github(token).get_repo(repo)
# --- event utils
@functools.lru_cache()
def _get_event_data():
ret = json.load(open(os.environ["GITHUB_EVENT_PATH"]))
pp(ret)
return ret
def is_event_new_issue():
data = _get_event_data()
try:
return data['action'] == 'opened' and 'issue' in data
except KeyError:
return False
def is_event_new_pr():
data = _get_event_data()
try:
return data['action'] == 'opened' and 'pull_request' in data
except KeyError:
return False
def get_issue():
data = _get_event_data()
try:
num = data['issue']['number']
except KeyError:
num = data['pull_request']['number']
return get_repo().get_issue(number=num)
# --- actions
def log(msg):
if '\n' in msg or "\r\n" in msg:
print(">>>\n%s\n<<<" % msg, flush=True)
else:
print(">>> %s <<<" % msg, flush=True)
def add_label(issue, label):
def should_add(issue, label):
if has_label(issue, label):
log("already has label %r" % (label))
return False
for left, right in ILLOGICAL_PAIRS:
if label == left and has_label(issue, right):
log("already has label" % (label))
return False
return not has_label(issue, label)
if not should_add(issue, label):
log("should not add label %r" % label)
return
log("add label %r" % label)
issue.add_to_labels(label)
def _guess_labels_from_text(text):
assert isinstance(text, str), text
for label, keywords in LABELS_MAP.items():
for keyword in keywords:
if keyword.lower() in text.lower():
yield (label, keyword)
def add_labels_from_text(issue, text):
assert isinstance(text, str), text
for label, keyword in _guess_labels_from_text(text):
add_label(issue, label)
def add_labels_from_new_body(issue, text):
assert isinstance(text, str), text
log("start searching for template lines in new issue/PR body")
# add os label
r = re.search(r"\* OS:.*?\n", text)
log("search for 'OS: ...' line")
if r:
log("found")
add_labels_from_text(issue, r.group(0))
else:
log("not found")
# add bug/enhancement label
log("search for 'Bug fix: y/n' line")
r = re.search(r"\* Bug fix:.*?\n", text)
if is_pr(issue) and \
r is not None and \
not has_label(issue, "bug") and \
not has_label(issue, "enhancement"):
log("found")
s = r.group(0).lower()
if 'yes' in s:
add_label(issue, 'bug')
else:
add_label(issue, 'enhancement')
else:
log("not found")
# add type labels
log("search for 'Type: ...' line")
r = re.search(r"\* Type:.*?\n", text)
if r:
log("found")
s = r.group(0).lower()
if 'doc' in s:
add_label(issue, 'doc')
if 'performance' in s:
add_label(issue, 'performance')
if 'scripts' in s:
add_label(issue, 'scripts')
if 'tests' in s:
add_label(issue, 'tests')
if 'wheels' in s:
add_label(issue, 'wheels')
if 'new-api' in s:
add_label(issue, 'new-api')
if 'new-platform' in s:
add_label(issue, 'new-platform')
else:
log("not found")
# --- events
def on_new_issue(issue):
def has_text(text):
return text in issue.title.lower() or \
(issue.body and text in issue.body.lower())
def body_mentions_python_h():
if not issue.body:
return False
body = issue.body.replace(' ', '')
return "#include<Python.h>\n^~~~" in body or \
"#include<Python.h>\r\n^~~~" in body
log("searching for missing Python.h")
if has_text("missing python.h") or \
has_text("python.h: no such file or directory") or \
body_mentions_python_h():
log("found mention of Python.h")
issue.create_comment(REPLY_MISSING_PYTHON_HEADERS)
issue.edit(state='closed')
return
def on_new_pr(issue):
pass
# pr = get_repo().get_pull(issue.number)
# files = [x.filename for x in list(pr.get_files())]
# if "HISTORY.rst" not in files:
# issue.create_comment(REPLY_UPDATE_CHANGELOG)
def main():
issue = get_issue()
stype = "PR" if is_pr(issue) else "issue"
log("running issue bot for %s %r" % (stype, issue))
if is_event_new_issue():
log("created new issue %s" % issue)
add_labels_from_text(issue, issue.title)
if issue.body:
add_labels_from_new_body(issue, issue.body)
on_new_issue(issue)
elif is_event_new_pr():
log("created new PR %s" % issue)
add_labels_from_text(issue, issue.title)
if issue.body:
add_labels_from_new_body(issue, issue.body)
on_new_pr(issue)
else:
log("unhandled event")
if __name__ == '__main__':
main()
| 9,551 | 26.527378 | 78 | py |
psutil | psutil-master/.github/workflows/issues.yml | # Fired by Github Actions every time an issue, PR or comment is created.
name: issues
on:
issues:
types: [opened]
pull_request:
typed: [opened]
issue_comment:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
# install python
- uses: actions/checkout@v3
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
# install deps
- name: Install deps
run: python3 -m pip install PyGithub
# run
- name: Run
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
PYTHONUNBUFFERED=1 PYTHONWARNINGS=always python3 .github/workflows/issues.py
| 680 | 20.28125 | 84 | yml |
psutil | psutil-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# psutil documentation build configuration file, created by
# sphinx-quickstart on Wed Oct 19 21:54:30 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
import datetime
import os
PROJECT_NAME = "psutil"
AUTHOR = u"Giampaolo Rodola"
THIS_YEAR = str(datetime.datetime.now().year)
HERE = os.path.abspath(os.path.dirname(__file__))
def get_version():
INIT = os.path.abspath(os.path.join(HERE, '../psutil/__init__.py'))
with open(INIT, 'r') as f:
for line in f:
if line.startswith('__version__'):
ret = eval(line.strip().split(' = ')[1])
assert ret.count('.') == 2, ret
for num in ret.split('.'):
assert num.isdigit(), ret
return ret
else:
raise ValueError("couldn't find version string")
VERSION = get_version()
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.imgmath',
'sphinx.ext.viewcode',
'sphinx.ext.intersphinx']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = PROJECT_NAME
copyright = '2009-%s, %s' % (THIS_YEAR, AUTHOR)
author = AUTHOR
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = VERSION
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "eng"
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'DEVGUIDE.rst']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = u'psutil v1.0'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or
# 32x32 pixels large.
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = '%s-doc' % PROJECT_NAME
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'psutil.tex', u'psutil Documentation',
AUTHOR, 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'psutil', u'psutil Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'psutil', u'psutil Documentation',
author, 'psutil', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
html_context = {
'css_files': [
'https://media.readthedocs.org/css/sphinx_rtd_theme.css',
'https://media.readthedocs.org/css/readthedocs-doc-embed.css',
'_static/css/custom.css',
],
}
| 10,839 | 27.753316 | 79 | py |
psutil | psutil-master/docs/_static/css/custom.css | .wy-nav-content {
max-width: 100% !important;
padding: 15px !important;
}
.rst-content dl:not(.docutils) {
margin: 0px 0px 0px 0px !important;
}
.data dd {
margin-bottom: 0px !important;
}
.data .descname {
border-right:10px !important;
}
.local-toc li ul li {
padding-left: 20px !important;
}
.rst-content ul p {
margin-bottom: 0px !important;
}
.document td {
padding-bottom: 0px !important;
}
.document th {
padding-top: 0px !important;
padding-bottom: 0px !important;
}
.document th p {
margin-bottom: 0px !important;
}
.document th p {
}
.function .descclassname {
font-weight: normal !important;
}
.class .descclassname {
font-weight: normal !important;
}
.admonition.warning {
padding-top: 2px !important;
padding-bottom: 2px !important;
}
.admonition.note {
padding-top: 2px !important;
padding-bottom: 2px !important;
}
.rst-content dl:not(.docutils) dt {
color: #555;
}
.sig-paren {
padding-left: 2px;
padding-right: 2px;
}
h1, h2, h3 {
background: #eee;
padding: 5px;
border-bottom: 1px solid #ccc;
}
h1 {
font-size: 35px;
}
.admonition.warning {
padding-top: 5px !important;
padding-bottom: 5px !important;
}
.admonition.warning p {
margin-bottom: 5px !important;
}
.admonition.note {
padding-top: 5px !important;
padding-bottom: 5px !important;
}
.admonition.note p {
margin-bottom: 5px !important;
backround-color: rgb(238, 255, 204) !important;
}
.codeblock div[class^='highlight'], pre.literal-block div[class^='highlight'], .rst-content .literal-block div[class^='highlight'], div[class^='highlight'] div[class^='highlight'] {
background-color: #eeffcc !important;
}
.highlight .hll {
background-color: #ffffcc
}
.highlight {
background: #eeffcc;
}
.highlight-default, .highlight-python {
border-radius: 3px !important;
border: 1px solid #ac9 !important;
}
.highlight .c {
color: #408090;
font-style: italic
}
.wy-side-nav-search {
background-color: grey !important
}
.highlight {
border-radius: 3px !important;
}
div.highlight-default {
margin-bottom: 10px !important;
}
pre {
padding: 5px !important;
}
/* ================================================================== */
/* Warnings and info boxes like python doc */
/* ================================================================== */
div.admonition {
margin-top: 10px !important;
margin-bottom: 10px !important;
}
div.warning {
background-color: #ffe4e4 !important;
border: 1px solid #f66 !important;
border-radius: 3px !important;
}
div.note {
background-color: #eee !important;
border: 1px solid #ccc !important;
border-radius: 3px !important;
}
div.admonition p.admonition-title + p {
display: inline !important;
}
p.admonition-title {
display: inline !important;
background: none !important;
color: black !important;
}
p.admonition-title:after {
content: ":" !important;
}
div.body div.admonition, div.body div.impl-detail {
}
.fa-exclamation-circle:before, .wy-inline-validate.wy-inline-validate-warning .wy-input-context:before, .wy-inline-validate.wy-inline-validate-info .wy-input-context:before, .rst-content .admonition-title:before {
display: none !important;
}
.note code {
background: #d6d6d6 !important;
}
/* ================================================================== */
/* Syntax highlight like Python doc.
/* ================================================================== */
/* Comment */
.highlight .err {
border: 1px solid #FF0000
}
/* Error */
.highlight .k {
color: #007020;
font-weight: bold
}
/* Keyword */
.highlight .o {
color: #666666
}
/* Operator */
.highlight .ch {
color: #408090;
font-style: italic
}
/* Comment.Hashbang */
.highlight .cm {
color: #408090;
font-style: italic
}
/* Comment.Multiline */
.highlight .cp {
color: #007020
}
/* Comment.Preproc */
.highlight .cpf {
color: #408090;
font-style: italic
}
/* Comment.PreprocFile */
.highlight .c1 {
color: #408090;
font-style: italic
}
/* Comment.Single */
.highlight .cs {
color: #408090;
background-color: #fff0f0
}
/* Comment.Special */
.highlight .gd {
color: #A00000
}
/* Generic.Deleted */
.highlight .ge {
font-style: italic
}
/* Generic.Emph */
.highlight .gr {
color: #FF0000
}
/* Generic.Error */
.highlight .gh {
color: #000080;
font-weight: bold
}
/* Generic.Heading */
.highlight .gi {
color: #00A000
}
/* Generic.Inserted */
.highlight .go {
color: #333333
}
/* Generic.Output */
.highlight .gp {
color: #c65d09;
font-weight: bold
}
/* Generic.Prompt */
.highlight .gs {
font-weight: bold
}
/* Generic.Strong */
.highlight .gu {
color: #800080;
font-weight: bold
}
/* Generic.Subheading */
.highlight .gt {
color: #0044DD
}
/* Generic.Traceback */
.highlight .kc {
color: #007020;
font-weight: bold
}
/* Keyword.Constant */
.highlight .kd {
color: #007020;
font-weight: bold
}
/* Keyword.Declaration */
.highlight .kn {
color: #007020;
font-weight: bold
}
/* Keyword.Namespace */
.highlight .kp {
color: #007020
}
/* Keyword.Pseudo */
.highlight .kr {
color: #007020;
font-weight: bold
}
/* Keyword.Reserved */
.highlight .kt {
color: #902000
}
/* Keyword.Type */
.highlight .m {
color: #208050
}
/* Literal.Number */
.highlight .s {
color: #4070a0
}
/* Literal.String */
.highlight .na {
color: #4070a0
}
/* Name.Attribute */
.highlight .nb {
color: #007020
}
/* Name.Builtin */
.highlight .nc {
color: #0e84b5;
font-weight: bold
}
/* Name.Class */
.highlight .no {
color: #60add5
}
/* Name.Constant */
.highlight .nd {
color: #555555;
font-weight: bold
}
/* Name.Decorator */
.highlight .ni {
color: #d55537;
font-weight: bold
}
/* Name.Entity */
.highlight .ne {
color: #007020
}
/* Name.Exception */
.highlight .nf {
color: #06287e
}
/* Name.Function */
.highlight .nl {
color: #002070;
font-weight: bold
}
/* Name.Label */
.highlight .nn {
color: #0e84b5;
font-weight: bold
}
/* Name.Namespace */
.highlight .nt {
color: #062873;
font-weight: bold
}
/* Name.Tag */
.highlight .nv {
color: #bb60d5
}
/* Name.Variable */
.highlight .ow {
color: #007020;
font-weight: bold
}
/* Operator.Word */
.highlight .w {
color: #bbbbbb
}
/* Text.Whitespace */
.highlight .mb {
color: #208050
}
/* Literal.Number.Bin */
.highlight .mf {
color: #208050
}
/* Literal.Number.Float */
.highlight .mh {
color: #208050
}
/* Literal.Number.Hex */
.highlight .mi {
color: #208050
}
/* Literal.Number.Integer */
.highlight .mo {
color: #208050
}
/* Literal.Number.Oct */
.highlight .sa {
color: #4070a0
}
/* Literal.String.Affix */
.highlight .sb {
color: #4070a0
}
/* Literal.String.Backtick */
.highlight .sc {
color: #4070a0
}
/* Literal.String.Char */
.highlight .dl {
color: #4070a0
}
/* Literal.String.Delimiter */
.highlight .sd {
color: #4070a0;
font-style: italic
}
/* Literal.String.Doc */
.highlight .s2 {
color: #4070a0
}
/* Literal.String.Double */
.highlight .se {
color: #4070a0;
font-weight: bold
}
/* Literal.String.Escape */
.highlight .sh {
color: #4070a0
}
/* Literal.String.Heredoc */
.highlight .si {
color: #70a0d0;
font-style: italic
}
/* Literal.String.Interpol */
.highlight .sx {
color: #c65d09
}
/* Literal.String.Other */
.highlight .sr {
color: #235388
}
/* Literal.String.Regex */
.highlight .s1 {
color: #4070a0
}
/* Literal.String.Single */
.highlight .ss {
color: #517918
}
/* Literal.String.Symbol */
.highlight .bp {
color: #007020
}
/* Name.Builtin.Pseudo */
.highlight .fm {
color: #06287e
}
/* Name.Function.Magic */
.highlight .vc {
color: #bb60d5
}
/* Name.Variable.Class */
.highlight .vg {
color: #bb60d5
}
/* Name.Variable.Global */
.highlight .vi {
color: #bb60d5
}
/* Name.Variable.Instance */
.highlight .vm {
color: #bb60d5
}
/* Name.Variable.Magic */
.highlight .il {
color: #208050
}
| 8,199 | 14.213358 | 213 | css |
psutil | psutil-master/psutil/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""psutil is a cross-platform library for retrieving information on
running processes and system utilization (CPU, memory, disks, network,
sensors) in Python. Supported platforms:
- Linux
- Windows
- macOS
- FreeBSD
- OpenBSD
- NetBSD
- Sun Solaris
- AIX
Works with Python versions 2.7 and 3.4+.
"""
from __future__ import division
import collections
import contextlib
import datetime
import functools
import os
import signal
import subprocess
import sys
import threading
import time
try:
import pwd
except ImportError:
pwd = None
from . import _common
from ._common import AIX
from ._common import BSD
from ._common import CONN_CLOSE
from ._common import CONN_CLOSE_WAIT
from ._common import CONN_CLOSING
from ._common import CONN_ESTABLISHED
from ._common import CONN_FIN_WAIT1
from ._common import CONN_FIN_WAIT2
from ._common import CONN_LAST_ACK
from ._common import CONN_LISTEN
from ._common import CONN_NONE
from ._common import CONN_SYN_RECV
from ._common import CONN_SYN_SENT
from ._common import CONN_TIME_WAIT
from ._common import FREEBSD # NOQA
from ._common import LINUX
from ._common import MACOS
from ._common import NETBSD # NOQA
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import OPENBSD # NOQA
from ._common import OSX # deprecated alias
from ._common import POSIX # NOQA
from ._common import POWER_TIME_UNKNOWN
from ._common import POWER_TIME_UNLIMITED
from ._common import STATUS_DEAD
from ._common import STATUS_DISK_SLEEP
from ._common import STATUS_IDLE
from ._common import STATUS_LOCKED
from ._common import STATUS_PARKED
from ._common import STATUS_RUNNING
from ._common import STATUS_SLEEPING
from ._common import STATUS_STOPPED
from ._common import STATUS_TRACING_STOP
from ._common import STATUS_WAITING
from ._common import STATUS_WAKING
from ._common import STATUS_ZOMBIE
from ._common import SUNOS
from ._common import WINDOWS
from ._common import AccessDenied
from ._common import Error
from ._common import NoSuchProcess
from ._common import TimeoutExpired
from ._common import ZombieProcess
from ._common import memoize_when_activated
from ._common import wrap_numbers as _wrap_numbers
from ._compat import PY3 as _PY3
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import SubprocessTimeoutExpired as _SubprocessTimeoutExpired
from ._compat import long
if LINUX:
# This is public API and it will be retrieved from _pslinux.py
# via sys.modules.
PROCFS_PATH = "/proc"
from . import _pslinux as _psplatform
from ._pslinux import IOPRIO_CLASS_BE # NOQA
from ._pslinux import IOPRIO_CLASS_IDLE # NOQA
from ._pslinux import IOPRIO_CLASS_NONE # NOQA
from ._pslinux import IOPRIO_CLASS_RT # NOQA
elif WINDOWS:
from . import _pswindows as _psplatform
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA
from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA
from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA
from ._pswindows import CONN_DELETE_TCB # NOQA
from ._pswindows import IOPRIO_HIGH # NOQA
from ._pswindows import IOPRIO_LOW # NOQA
from ._pswindows import IOPRIO_NORMAL # NOQA
from ._pswindows import IOPRIO_VERYLOW # NOQA
elif MACOS:
from . import _psosx as _psplatform
elif BSD:
from . import _psbsd as _psplatform
elif SUNOS:
from . import _pssunos as _psplatform
from ._pssunos import CONN_BOUND # NOQA
from ._pssunos import CONN_IDLE # NOQA
# This is public writable API which is read from _pslinux.py and
# _pssunos.py via sys.modules.
PROCFS_PATH = "/proc"
elif AIX:
from . import _psaix as _psplatform
# This is public API and it will be retrieved from _pslinux.py
# via sys.modules.
PROCFS_PATH = "/proc"
else: # pragma: no cover
raise NotImplementedError('platform %s is not supported' % sys.platform)
__all__ = [
# exceptions
"Error", "NoSuchProcess", "ZombieProcess", "AccessDenied",
"TimeoutExpired",
# constants
"version_info", "__version__",
"STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
"STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
"STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED",
"STATUS_PARKED",
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
# "CONN_IDLE", "CONN_BOUND",
"AF_LINK",
"NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN",
"POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED",
"BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX",
"SUNOS", "WINDOWS", "AIX",
# "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA",
# "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE",
# "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE",
# "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING",
# classes
"Process", "Popen",
# functions
"pid_exists", "pids", "process_iter", "wait_procs", # proc
"virtual_memory", "swap_memory", # memory
"cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu
"cpu_stats", # "cpu_freq", "getloadavg"
"net_io_counters", "net_connections", "net_if_addrs", # network
"net_if_stats",
"disk_io_counters", "disk_partitions", "disk_usage", # disk
# "sensors_temperatures", "sensors_battery", "sensors_fans" # sensors
"users", "boot_time", # others
]
__all__.extend(_psplatform.__extra__all__)
# Linux, FreeBSD
if hasattr(_psplatform.Process, "rlimit"):
# Populate global namespace with RLIM* constants.
from . import _psutil_posix
_globals = globals()
_name = None
for _name in dir(_psutil_posix):
if _name.startswith('RLIM') and _name.isupper():
_globals[_name] = getattr(_psutil_posix, _name)
__all__.append(_name)
del _globals, _name
AF_LINK = _psplatform.AF_LINK
__author__ = "Giampaolo Rodola'"
__version__ = "5.9.5"
version_info = tuple([int(num) for num in __version__.split('.')])
_timer = getattr(time, 'monotonic', time.time)
_TOTAL_PHYMEM = None
_LOWEST_PID = None
_SENTINEL = object()
# Sanity check in case the user messed up with psutil installation
# or did something weird with sys.path. In this case we might end
# up importing a python module using a C extension module which
# was compiled for a different version of psutil.
# We want to prevent that by failing sooner rather than later.
# See: https://github.com/giampaolo/psutil/issues/564
if (int(__version__.replace('.', '')) !=
getattr(_psplatform.cext, 'version', None)):
msg = "version conflict: %r C extension module was built for another " \
"version of psutil" % _psplatform.cext.__file__
if hasattr(_psplatform.cext, 'version'):
msg += " (%s instead of %s)" % (
'.'.join([x for x in str(_psplatform.cext.version)]), __version__)
else:
msg += " (different than %s)" % __version__
msg += "; you may try to 'pip uninstall psutil', manually remove %s" % (
getattr(_psplatform.cext, "__file__",
"the existing psutil install directory"))
msg += " or clean the virtual env somehow, then reinstall"
raise ImportError(msg)
# =====================================================================
# --- Utils
# =====================================================================
if hasattr(_psplatform, 'ppid_map'):
# Faster version (Windows and Linux).
_ppid_map = _psplatform.ppid_map
else: # pragma: no cover
def _ppid_map():
"""Return a {pid: ppid, ...} dict for all running processes in
one shot. Used to speed up Process.children().
"""
ret = {}
for pid in pids():
try:
ret[pid] = _psplatform.Process(pid).ppid()
except (NoSuchProcess, ZombieProcess):
pass
return ret
def _assert_pid_not_reused(fun):
"""Decorator which raises NoSuchProcess in case a process is no
longer running or its PID has been reused.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
if not self.is_running():
if self._pid_reused:
msg = "process no longer exists and its PID has been reused"
else:
msg = None
raise NoSuchProcess(self.pid, self._name, msg=msg)
return fun(self, *args, **kwargs)
return wrapper
def _pprint_secs(secs):
"""Format seconds in a human readable form."""
now = time.time()
secs_ago = int(now - secs)
if secs_ago < 60 * 60 * 24:
fmt = "%H:%M:%S"
else:
fmt = "%Y-%m-%d %H:%M:%S"
return datetime.datetime.fromtimestamp(secs).strftime(fmt)
# =====================================================================
# --- Process class
# =====================================================================
class Process(object):
"""Represents an OS process with the given PID.
If PID is omitted current process PID (os.getpid()) is used.
Raise NoSuchProcess if PID does not exist.
Note that most of the methods of this class do not make sure
the PID of the process being queried has been reused over time.
That means you might end up retrieving an information referring
to another process in case the original one this instance
refers to is gone in the meantime.
The only exceptions for which process identity is pre-emptively
checked and guaranteed are:
- parent()
- children()
- nice() (set)
- ionice() (set)
- rlimit() (set)
- cpu_affinity (set)
- suspend()
- resume()
- send_signal()
- terminate()
- kill()
To prevent this problem for all other methods you can:
- use is_running() before querying the process
- if you're continuously iterating over a set of Process
instances use process_iter() which pre-emptively checks
process identity for every yielded instance
"""
def __init__(self, pid=None):
self._init(pid)
def _init(self, pid, _ignore_nsp=False):
if pid is None:
pid = os.getpid()
else:
if not _PY3 and not isinstance(pid, (int, long)):
raise TypeError('pid must be an integer (got %r)' % pid)
if pid < 0:
raise ValueError('pid must be a positive integer (got %s)'
% pid)
try:
_psplatform.cext.check_pid_range(pid)
except OverflowError:
raise NoSuchProcess(
pid,
msg='process PID out of range (got %s)' % pid,
)
self._pid = pid
self._name = None
self._exe = None
self._create_time = None
self._gone = False
self._pid_reused = False
self._hash = None
self._lock = threading.RLock()
# used for caching on Windows only (on POSIX ppid may change)
self._ppid = None
# platform-specific modules define an _psplatform.Process
# implementation class
self._proc = _psplatform.Process(pid)
self._last_sys_cpu_times = None
self._last_proc_cpu_times = None
self._exitcode = _SENTINEL
# cache creation time for later use in is_running() method
try:
self.create_time()
except AccessDenied:
# We should never get here as AFAIK we're able to get
# process creation time on all platforms even as a
# limited user.
pass
except ZombieProcess:
# Zombies can still be queried by this class (although
# not always) and pids() return them so just go on.
pass
except NoSuchProcess:
if not _ignore_nsp:
raise NoSuchProcess(pid, msg='process PID not found')
else:
self._gone = True
# This pair is supposed to identify a Process instance
# univocally over time (the PID alone is not enough as
# it might refer to a process whose PID has been reused).
# This will be used later in __eq__() and is_running().
self._ident = (self.pid, self._create_time)
def __str__(self):
info = collections.OrderedDict()
info["pid"] = self.pid
if self._name:
info['name'] = self._name
with self.oneshot():
try:
info["name"] = self.name()
info["status"] = self.status()
except ZombieProcess:
info["status"] = "zombie"
except NoSuchProcess:
info["status"] = "terminated"
except AccessDenied:
pass
if self._exitcode not in (_SENTINEL, None):
info["exitcode"] = self._exitcode
if self._create_time:
info['started'] = _pprint_secs(self._create_time)
return "%s.%s(%s)" % (
self.__class__.__module__,
self.__class__.__name__,
", ".join(["%s=%r" % (k, v) for k, v in info.items()]))
__repr__ = __str__
def __eq__(self, other):
# Test for equality with another Process object based
# on PID and creation time.
if not isinstance(other, Process):
return NotImplemented
return self._ident == other._ident
def __ne__(self, other):
return not self == other
def __hash__(self):
if self._hash is None:
self._hash = hash(self._ident)
return self._hash
@property
def pid(self):
"""The process PID."""
return self._pid
# --- utility methods
@contextlib.contextmanager
def oneshot(self):
"""Utility context manager which considerably speeds up the
retrieval of multiple process information at the same time.
Internally different process info (e.g. name, ppid, uids,
gids, ...) may be fetched by using the same routine, but
only one information is returned and the others are discarded.
When using this context manager the internal routine is
executed once (in the example below on name()) and the
other info are cached.
The cache is cleared when exiting the context manager block.
The advice is to use this every time you retrieve more than
one information about the process. If you're lucky, you'll
get a hell of a speedup.
>>> import psutil
>>> p = psutil.Process()
>>> with p.oneshot():
... p.name() # collect multiple info
... p.cpu_times() # return cached value
... p.cpu_percent() # return cached value
... p.create_time() # return cached value
...
>>>
"""
with self._lock:
if hasattr(self, "_cache"):
# NOOP: this covers the use case where the user enters the
# context twice:
#
# >>> with p.oneshot():
# ... with p.oneshot():
# ...
#
# Also, since as_dict() internally uses oneshot()
# I expect that the code below will be a pretty common
# "mistake" that the user will make, so let's guard
# against that:
#
# >>> with p.oneshot():
# ... p.as_dict()
# ...
yield
else:
try:
# cached in case cpu_percent() is used
self.cpu_times.cache_activate(self)
# cached in case memory_percent() is used
self.memory_info.cache_activate(self)
# cached in case parent() is used
self.ppid.cache_activate(self)
# cached in case username() is used
if POSIX:
self.uids.cache_activate(self)
# specific implementation cache
self._proc.oneshot_enter()
yield
finally:
self.cpu_times.cache_deactivate(self)
self.memory_info.cache_deactivate(self)
self.ppid.cache_deactivate(self)
if POSIX:
self.uids.cache_deactivate(self)
self._proc.oneshot_exit()
def as_dict(self, attrs=None, ad_value=None):
"""Utility method returning process information as a
hashable dictionary.
If *attrs* is specified it must be a list of strings
reflecting available Process class' attribute names
(e.g. ['cpu_times', 'name']) else all public (read
only) attributes are assumed.
*ad_value* is the value which gets assigned in case
AccessDenied or ZombieProcess exception is raised when
retrieving that particular process information.
"""
valid_names = _as_dict_attrnames
if attrs is not None:
if not isinstance(attrs, (list, tuple, set, frozenset)):
raise TypeError("invalid attrs type %s" % type(attrs))
attrs = set(attrs)
invalid_names = attrs - valid_names
if invalid_names:
raise ValueError("invalid attr name%s %s" % (
"s" if len(invalid_names) > 1 else "",
", ".join(map(repr, invalid_names))))
retdict = {}
ls = attrs or valid_names
with self.oneshot():
for name in ls:
try:
if name == 'pid':
ret = self.pid
else:
meth = getattr(self, name)
ret = meth()
except (AccessDenied, ZombieProcess):
ret = ad_value
except NotImplementedError:
# in case of not implemented functionality (may happen
# on old or exotic systems) we want to crash only if
# the user explicitly asked for that particular attr
if attrs:
raise
continue
retdict[name] = ret
return retdict
def parent(self):
"""Return the parent process as a Process object pre-emptively
checking whether PID has been reused.
If no parent is known return None.
"""
lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0]
if self.pid == lowest_pid:
return None
ppid = self.ppid()
if ppid is not None:
ctime = self.create_time()
try:
parent = Process(ppid)
if parent.create_time() <= ctime:
return parent
# ...else ppid has been reused by another process
except NoSuchProcess:
pass
def parents(self):
"""Return the parents of this process as a list of Process
instances. If no parents are known return an empty list.
"""
parents = []
proc = self.parent()
while proc is not None:
parents.append(proc)
proc = proc.parent()
return parents
def is_running(self):
"""Return whether this process is running.
It also checks if PID has been reused by another process in
which case return False.
"""
if self._gone or self._pid_reused:
return False
try:
# Checking if PID is alive is not enough as the PID might
# have been reused by another process: we also want to
# verify process identity.
# Process identity / uniqueness over time is guaranteed by
# (PID + creation time) and that is verified in __eq__.
self._pid_reused = self != Process(self.pid)
return not self._pid_reused
except ZombieProcess:
# We should never get here as it's already handled in
# Process.__init__; here just for extra safety.
return True
except NoSuchProcess:
self._gone = True
return False
# --- actual API
@memoize_when_activated
def ppid(self):
"""The process parent PID.
On Windows the return value is cached after first call.
"""
# On POSIX we don't want to cache the ppid as it may unexpectedly
# change to 1 (init) in case this process turns into a zombie:
# https://github.com/giampaolo/psutil/issues/321
# http://stackoverflow.com/questions/356722/
# XXX should we check creation time here rather than in
# Process.parent()?
if POSIX:
return self._proc.ppid()
else: # pragma: no cover
self._ppid = self._ppid or self._proc.ppid()
return self._ppid
def name(self):
"""The process name. The return value is cached after first call."""
# Process name is only cached on Windows as on POSIX it may
# change, see:
# https://github.com/giampaolo/psutil/issues/692
if WINDOWS and self._name is not None:
return self._name
name = self._proc.name()
if POSIX and len(name) >= 15:
# On UNIX the name gets truncated to the first 15 characters.
# If it matches the first part of the cmdline we return that
# one instead because it's usually more explicative.
# Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
try:
cmdline = self.cmdline()
except (AccessDenied, ZombieProcess):
# Just pass and return the truncated name: it's better
# than nothing. Note: there are actual cases where a
# zombie process can return a name() but not a
# cmdline(), see:
# https://github.com/giampaolo/psutil/issues/2239
pass
else:
if cmdline:
extended_name = os.path.basename(cmdline[0])
if extended_name.startswith(name):
name = extended_name
self._name = name
self._proc._name = name
return name
def exe(self):
"""The process executable as an absolute path.
May also be an empty string.
The return value is cached after first call.
"""
def guess_it(fallback):
# try to guess exe from cmdline[0] in absence of a native
# exe representation
cmdline = self.cmdline()
if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
exe = cmdline[0] # the possible exe
# Attempt to guess only in case of an absolute path.
# It is not safe otherwise as the process might have
# changed cwd.
if (os.path.isabs(exe) and
os.path.isfile(exe) and
os.access(exe, os.X_OK)):
return exe
if isinstance(fallback, AccessDenied):
raise fallback
return fallback
if self._exe is None:
try:
exe = self._proc.exe()
except AccessDenied as err:
return guess_it(fallback=err)
else:
if not exe:
# underlying implementation can legitimately return an
# empty string; if that's the case we don't want to
# raise AD while guessing from the cmdline
try:
exe = guess_it(fallback=exe)
except AccessDenied:
pass
self._exe = exe
return self._exe
def cmdline(self):
"""The command line this process has been called with."""
return self._proc.cmdline()
def status(self):
"""The process current status as a STATUS_* constant."""
try:
return self._proc.status()
except ZombieProcess:
return STATUS_ZOMBIE
def username(self):
"""The name of the user that owns the process.
On UNIX this is calculated by using *real* process uid.
"""
if POSIX:
if pwd is None:
# might happen if python was installed from sources
raise ImportError(
"requires pwd module shipped with standard python")
real_uid = self.uids().real
try:
return pwd.getpwuid(real_uid).pw_name
except KeyError:
# the uid can't be resolved by the system
return str(real_uid)
else:
return self._proc.username()
def create_time(self):
"""The process creation time as a floating point number
expressed in seconds since the epoch.
The return value is cached after first call.
"""
if self._create_time is None:
self._create_time = self._proc.create_time()
return self._create_time
def cwd(self):
"""Process current working directory as an absolute path."""
return self._proc.cwd()
def nice(self, value=None):
"""Get or set process niceness (priority)."""
if value is None:
return self._proc.nice_get()
else:
if not self.is_running():
raise NoSuchProcess(self.pid, self._name)
self._proc.nice_set(value)
if POSIX:
@memoize_when_activated
def uids(self):
"""Return process UIDs as a (real, effective, saved)
namedtuple.
"""
return self._proc.uids()
def gids(self):
"""Return process GIDs as a (real, effective, saved)
namedtuple.
"""
return self._proc.gids()
def terminal(self):
"""The terminal associated with this process, if any,
else None.
"""
return self._proc.terminal()
def num_fds(self):
"""Return the number of file descriptors opened by this
process (POSIX only).
"""
return self._proc.num_fds()
# Linux, BSD, AIX and Windows only
if hasattr(_psplatform.Process, "io_counters"):
def io_counters(self):
"""Return process I/O statistics as a
(read_count, write_count, read_bytes, write_bytes)
namedtuple.
Those are the number of read/write calls performed and the
amount of bytes read and written by the process.
"""
return self._proc.io_counters()
# Linux and Windows
if hasattr(_psplatform.Process, "ionice_get"):
def ionice(self, ioclass=None, value=None):
"""Get or set process I/O niceness (priority).
On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
*value* is a number which goes from 0 to 7. The higher the
value, the lower the I/O priority of the process.
On Windows only *ioclass* is used and it can be set to 2
(normal), 1 (low) or 0 (very low).
Available on Linux and Windows > Vista only.
"""
if ioclass is None:
if value is not None:
raise ValueError("'ioclass' argument must be specified")
return self._proc.ionice_get()
else:
return self._proc.ionice_set(ioclass, value)
# Linux / FreeBSD only
if hasattr(_psplatform.Process, "rlimit"):
def rlimit(self, resource, limits=None):
"""Get or set process resource limits as a (soft, hard)
tuple.
*resource* is one of the RLIMIT_* constants.
*limits* is supposed to be a (soft, hard) tuple.
See "man prlimit" for further info.
Available on Linux and FreeBSD only.
"""
return self._proc.rlimit(resource, limits)
# Windows, Linux and FreeBSD only
if hasattr(_psplatform.Process, "cpu_affinity_get"):
def cpu_affinity(self, cpus=None):
"""Get or set process CPU affinity.
If specified, *cpus* must be a list of CPUs for which you
want to set the affinity (e.g. [0, 1]).
If an empty list is passed, all egible CPUs are assumed
(and set).
(Windows, Linux and BSD only).
"""
if cpus is None:
return sorted(set(self._proc.cpu_affinity_get()))
else:
if not cpus:
if hasattr(self._proc, "_get_eligible_cpus"):
cpus = self._proc._get_eligible_cpus()
else:
cpus = tuple(range(len(cpu_times(percpu=True))))
self._proc.cpu_affinity_set(list(set(cpus)))
# Linux, FreeBSD, SunOS
if hasattr(_psplatform.Process, "cpu_num"):
def cpu_num(self):
"""Return what CPU this process is currently running on.
The returned number should be <= psutil.cpu_count()
and <= len(psutil.cpu_percent(percpu=True)).
It may be used in conjunction with
psutil.cpu_percent(percpu=True) to observe the system
workload distributed across CPUs.
"""
return self._proc.cpu_num()
# All platforms has it, but maybe not in the future.
if hasattr(_psplatform.Process, "environ"):
def environ(self):
"""The environment variables of the process as a dict. Note: this
might not reflect changes made after the process started. """
return self._proc.environ()
if WINDOWS:
def num_handles(self):
"""Return the number of handles opened by this process
(Windows only).
"""
return self._proc.num_handles()
def num_ctx_switches(self):
"""Return the number of voluntary and involuntary context
switches performed by this process.
"""
return self._proc.num_ctx_switches()
def num_threads(self):
"""Return the number of threads used by this process."""
return self._proc.num_threads()
if hasattr(_psplatform.Process, "threads"):
def threads(self):
"""Return threads opened by process as a list of
(id, user_time, system_time) namedtuples representing
thread id and thread CPU times (user/system).
On OpenBSD this method requires root access.
"""
return self._proc.threads()
@_assert_pid_not_reused
def children(self, recursive=False):
"""Return the children of this process as a list of Process
instances, pre-emptively checking whether PID has been reused.
If *recursive* is True return all the parent descendants.
Example (A == this process):
A ─┐
│
├─ B (child) ─┐
│ └─ X (grandchild) ─┐
│ └─ Y (great grandchild)
├─ C (child)
└─ D (child)
>>> import psutil
>>> p = psutil.Process()
>>> p.children()
B, C, D
>>> p.children(recursive=True)
B, X, Y, C, D
Note that in the example above if process X disappears
process Y won't be listed as the reference to process A
is lost.
"""
ppid_map = _ppid_map()
ret = []
if not recursive:
for pid, ppid in ppid_map.items():
if ppid == self.pid:
try:
child = Process(pid)
# if child happens to be older than its parent
# (self) it means child's PID has been reused
if self.create_time() <= child.create_time():
ret.append(child)
except (NoSuchProcess, ZombieProcess):
pass
else:
# Construct a {pid: [child pids]} dict
reverse_ppid_map = collections.defaultdict(list)
for pid, ppid in ppid_map.items():
reverse_ppid_map[ppid].append(pid)
# Recursively traverse that dict, starting from self.pid,
# such that we only call Process() on actual children
seen = set()
stack = [self.pid]
while stack:
pid = stack.pop()
if pid in seen:
# Since pids can be reused while the ppid_map is
# constructed, there may be rare instances where
# there's a cycle in the recorded process "tree".
continue
seen.add(pid)
for child_pid in reverse_ppid_map[pid]:
try:
child = Process(child_pid)
# if child happens to be older than its parent
# (self) it means child's PID has been reused
intime = self.create_time() <= child.create_time()
if intime:
ret.append(child)
stack.append(child_pid)
except (NoSuchProcess, ZombieProcess):
pass
return ret
def cpu_percent(self, interval=None):
"""Return a float representing the current process CPU
utilization as a percentage.
When *interval* is 0.0 or None (default) compares process times
to system CPU times elapsed since last call, returning
immediately (non-blocking). That means that the first time
this is called it will return a meaningful 0.0 value.
When *interval* is > 0.0 compares process times to system CPU
times elapsed before and after the interval (blocking).
In this case is recommended for accuracy that this function
be called with at least 0.1 seconds between calls.
A value > 100.0 can be returned in case of processes running
multiple threads on different CPU cores.
The returned value is explicitly NOT split evenly between
all available logical CPUs. This means that a busy loop process
running on a system with 2 logical CPUs will be reported as
having 100% CPU utilization instead of 50%.
Examples:
>>> import psutil
>>> p = psutil.Process(os.getpid())
>>> # blocking
>>> p.cpu_percent(interval=1)
2.0
>>> # non-blocking (percentage since last call)
>>> p.cpu_percent(interval=None)
2.9
>>>
"""
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
raise ValueError("interval is not positive (got %r)" % interval)
num_cpus = cpu_count() or 1
def timer():
return _timer() * num_cpus
if blocking:
st1 = timer()
pt1 = self._proc.cpu_times()
time.sleep(interval)
st2 = timer()
pt2 = self._proc.cpu_times()
else:
st1 = self._last_sys_cpu_times
pt1 = self._last_proc_cpu_times
st2 = timer()
pt2 = self._proc.cpu_times()
if st1 is None or pt1 is None:
self._last_sys_cpu_times = st2
self._last_proc_cpu_times = pt2
return 0.0
delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
delta_time = st2 - st1
# reset values for next call in case of interval == None
self._last_sys_cpu_times = st2
self._last_proc_cpu_times = pt2
try:
# This is the utilization split evenly between all CPUs.
# E.g. a busy loop process on a 2-CPU-cores system at this
# point is reported as 50% instead of 100%.
overall_cpus_percent = ((delta_proc / delta_time) * 100)
except ZeroDivisionError:
# interval was too low
return 0.0
else:
# Note 1:
# in order to emulate "top" we multiply the value for the num
# of CPU cores. This way the busy process will be reported as
# having 100% (or more) usage.
#
# Note 2:
# taskmgr.exe on Windows differs in that it will show 50%
# instead.
#
# Note 3:
# a percentage > 100 is legitimate as it can result from a
# process with multiple threads running on different CPU
# cores (top does the same), see:
# http://stackoverflow.com/questions/1032357
# https://github.com/giampaolo/psutil/issues/474
single_cpu_percent = overall_cpus_percent * num_cpus
return round(single_cpu_percent, 1)
@memoize_when_activated
def cpu_times(self):
"""Return a (user, system, children_user, children_system)
namedtuple representing the accumulated process time, in
seconds.
This is similar to os.times() but per-process.
On macOS and Windows children_user and children_system are
always set to 0.
"""
return self._proc.cpu_times()
@memoize_when_activated
def memory_info(self):
"""Return a namedtuple with variable fields depending on the
platform, representing memory information about the process.
The "portable" fields available on all platforms are `rss` and `vms`.
All numbers are expressed in bytes.
"""
return self._proc.memory_info()
@_common.deprecated_method(replacement="memory_info")
def memory_info_ex(self):
return self.memory_info()
def memory_full_info(self):
"""This method returns the same information as memory_info(),
plus, on some platform (Linux, macOS, Windows), also provides
additional metrics (USS, PSS and swap).
The additional metrics provide a better representation of actual
process memory usage.
Namely USS is the memory which is unique to a process and which
would be freed if the process was terminated right now.
It does so by passing through the whole process address.
As such it usually requires higher user privileges than
memory_info() and is considerably slower.
"""
return self._proc.memory_full_info()
def memory_percent(self, memtype="rss"):
"""Compare process memory to total physical system memory and
calculate process memory utilization as a percentage.
*memtype* argument is a string that dictates what type of
process memory you want to compare against (defaults to "rss").
The list of available strings can be obtained like this:
>>> psutil.Process().memory_info()._fields
('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
"""
valid_types = list(_psplatform.pfullmem._fields)
if memtype not in valid_types:
raise ValueError("invalid memtype %r; valid types are %r" % (
memtype, tuple(valid_types)))
fun = self.memory_info if memtype in _psplatform.pmem._fields else \
self.memory_full_info
metrics = fun()
value = getattr(metrics, memtype)
# use cached value if available
total_phymem = _TOTAL_PHYMEM or virtual_memory().total
if not total_phymem > 0:
# we should never get here
raise ValueError(
"can't calculate process memory percent because "
"total physical system memory is not positive (%r)"
% total_phymem)
return (value / float(total_phymem)) * 100
if hasattr(_psplatform.Process, "memory_maps"):
def memory_maps(self, grouped=True):
"""Return process' mapped memory regions as a list of namedtuples
whose fields are variable depending on the platform.
If *grouped* is True the mapped regions with the same 'path'
are grouped together and the different memory fields are summed.
If *grouped* is False every mapped region is shown as a single
entity and the namedtuple will also include the mapped region's
address space ('addr') and permission set ('perms').
"""
it = self._proc.memory_maps()
if grouped:
d = {}
for tupl in it:
path = tupl[2]
nums = tupl[3:]
try:
d[path] = map(lambda x, y: x + y, d[path], nums)
except KeyError:
d[path] = nums
nt = _psplatform.pmmap_grouped
return [nt(path, *d[path]) for path in d] # NOQA
else:
nt = _psplatform.pmmap_ext
return [nt(*x) for x in it]
def open_files(self):
"""Return files opened by process as a list of
(path, fd) namedtuples including the absolute file name
and file descriptor number.
"""
return self._proc.open_files()
def connections(self, kind='inet'):
"""Return socket connections opened by process as a list of
(fd, family, type, laddr, raddr, status) namedtuples.
The *kind* parameter filters for connections that match the
following criteria:
+------------+----------------------------------------------------+
| Kind Value | Connections using |
+------------+----------------------------------------------------+
| inet | IPv4 and IPv6 |
| inet4 | IPv4 |
| inet6 | IPv6 |
| tcp | TCP |
| tcp4 | TCP over IPv4 |
| tcp6 | TCP over IPv6 |
| udp | UDP |
| udp4 | UDP over IPv4 |
| udp6 | UDP over IPv6 |
| unix | UNIX socket (both UDP and TCP protocols) |
| all | the sum of all the possible families and protocols |
+------------+----------------------------------------------------+
"""
return self._proc.connections(kind)
# --- signals
if POSIX:
def _send_signal(self, sig):
assert not self.pid < 0, self.pid
if self.pid == 0:
# see "man 2 kill"
raise ValueError(
"preventing sending signal to process with PID 0 as it "
"would affect every process in the process group of the "
"calling process (os.getpid()) instead of PID 0")
try:
os.kill(self.pid, sig)
except ProcessLookupError:
if OPENBSD and pid_exists(self.pid):
# We do this because os.kill() lies in case of
# zombie processes.
raise ZombieProcess(self.pid, self._name, self._ppid)
else:
self._gone = True
raise NoSuchProcess(self.pid, self._name)
except PermissionError:
raise AccessDenied(self.pid, self._name)
@_assert_pid_not_reused
def send_signal(self, sig):
"""Send a signal *sig* to process pre-emptively checking
whether PID has been reused (see signal module constants) .
On Windows only SIGTERM is valid and is treated as an alias
for kill().
"""
if POSIX:
self._send_signal(sig)
else: # pragma: no cover
self._proc.send_signal(sig)
@_assert_pid_not_reused
def suspend(self):
"""Suspend process execution with SIGSTOP pre-emptively checking
whether PID has been reused.
On Windows this has the effect of suspending all process threads.
"""
if POSIX:
self._send_signal(signal.SIGSTOP)
else: # pragma: no cover
self._proc.suspend()
@_assert_pid_not_reused
def resume(self):
"""Resume process execution with SIGCONT pre-emptively checking
whether PID has been reused.
On Windows this has the effect of resuming all process threads.
"""
if POSIX:
self._send_signal(signal.SIGCONT)
else: # pragma: no cover
self._proc.resume()
@_assert_pid_not_reused
def terminate(self):
"""Terminate the process with SIGTERM pre-emptively checking
whether PID has been reused.
On Windows this is an alias for kill().
"""
if POSIX:
self._send_signal(signal.SIGTERM)
else: # pragma: no cover
self._proc.kill()
@_assert_pid_not_reused
def kill(self):
"""Kill the current process with SIGKILL pre-emptively checking
whether PID has been reused.
"""
if POSIX:
self._send_signal(signal.SIGKILL)
else: # pragma: no cover
self._proc.kill()
def wait(self, timeout=None):
"""Wait for process to terminate and, if process is a children
of os.getpid(), also return its exit code, else None.
On Windows there's no such limitation (exit code is always
returned).
If the process is already terminated immediately return None
instead of raising NoSuchProcess.
If *timeout* (in seconds) is specified and process is still
alive raise TimeoutExpired.
To wait for multiple Process(es) use psutil.wait_procs().
"""
if timeout is not None and not timeout >= 0:
raise ValueError("timeout must be a positive integer")
if self._exitcode is not _SENTINEL:
return self._exitcode
self._exitcode = self._proc.wait(timeout)
return self._exitcode
# The valid attr names which can be processed by Process.as_dict().
_as_dict_attrnames = set(
[x for x in dir(Process) if not x.startswith('_') and x not in
['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit',
'memory_info_ex', 'oneshot']])
# =====================================================================
# --- Popen class
# =====================================================================
class Popen(Process):
"""Same as subprocess.Popen, but in addition it provides all
psutil.Process methods in a single class.
For the following methods which are common to both classes, psutil
implementation takes precedence:
* send_signal()
* terminate()
* kill()
This is done in order to avoid killing another process in case its
PID has been reused, fixing BPO-6973.
>>> import psutil
>>> from subprocess import PIPE
>>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
>>> p.name()
'python'
>>> p.uids()
user(real=1000, effective=1000, saved=1000)
>>> p.username()
'giampaolo'
>>> p.communicate()
('hi\n', None)
>>> p.terminate()
>>> p.wait(timeout=2)
0
>>>
"""
def __init__(self, *args, **kwargs):
# Explicitly avoid to raise NoSuchProcess in case the process
# spawned by subprocess.Popen terminates too quickly, see:
# https://github.com/giampaolo/psutil/issues/193
self.__subproc = subprocess.Popen(*args, **kwargs)
self._init(self.__subproc.pid, _ignore_nsp=True)
def __dir__(self):
return sorted(set(dir(Popen) + dir(subprocess.Popen)))
def __enter__(self):
if hasattr(self.__subproc, '__enter__'):
self.__subproc.__enter__()
return self
def __exit__(self, *args, **kwargs):
if hasattr(self.__subproc, '__exit__'):
return self.__subproc.__exit__(*args, **kwargs)
else:
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
try:
# Flushing a BufferedWriter may raise an error.
if self.stdin:
self.stdin.close()
finally:
# Wait for the process to terminate, to avoid zombies.
self.wait()
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
try:
return object.__getattribute__(self.__subproc, name)
except AttributeError:
raise AttributeError("%s instance has no attribute '%s'"
% (self.__class__.__name__, name))
def wait(self, timeout=None):
if self.__subproc.returncode is not None:
return self.__subproc.returncode
ret = super(Popen, self).wait(timeout)
self.__subproc.returncode = ret
return ret
# =====================================================================
# --- system processes related functions
# =====================================================================
def pids():
"""Return a list of current running PIDs."""
global _LOWEST_PID
ret = sorted(_psplatform.pids())
_LOWEST_PID = ret[0]
return ret
def pid_exists(pid):
"""Return True if given PID exists in the current process list.
This is faster than doing "pid in psutil.pids()" and
should be preferred.
"""
if pid < 0:
return False
elif pid == 0 and POSIX:
# On POSIX we use os.kill() to determine PID existence.
# According to "man 2 kill" PID 0 has a special meaning
# though: it refers to <<every process in the process
# group of the calling process>> and that is not we want
# to do here.
return pid in pids()
else:
return _psplatform.pid_exists(pid)
_pmap = {}
def process_iter(attrs=None, ad_value=None):
"""Return a generator yielding a Process instance for all
running processes.
Every new Process instance is only created once and then cached
into an internal table which is updated every time this is used.
Cached Process instances are checked for identity so that you're
safe in case a PID has been reused by another process, in which
case the cached instance is updated.
The sorting order in which processes are yielded is based on
their PIDs.
*attrs* and *ad_value* have the same meaning as in
Process.as_dict(). If *attrs* is specified as_dict() is called
and the resulting dict is stored as a 'info' attribute attached
to returned Process instance.
If *attrs* is an empty list it will retrieve all process info
(slow).
"""
global _pmap
def add(pid):
proc = Process(pid)
if attrs is not None:
proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value)
pmap[proc.pid] = proc
return proc
def remove(pid):
pmap.pop(pid, None)
pmap = _pmap.copy()
a = set(pids())
b = set(pmap.keys())
new_pids = a - b
gone_pids = b - a
for pid in gone_pids:
remove(pid)
try:
ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items()))
for pid, proc in ls:
try:
if proc is None: # new process
yield add(pid)
else:
# use is_running() to check whether PID has been
# reused by another process in which case yield a
# new Process instance
if proc.is_running():
if attrs is not None:
proc.info = proc.as_dict(
attrs=attrs, ad_value=ad_value)
yield proc
else:
yield add(pid)
except NoSuchProcess:
remove(pid)
except AccessDenied:
# Process creation time can't be determined hence there's
# no way to tell whether the pid of the cached process
# has been reused. Just return the cached version.
if proc is None and pid in pmap:
try:
yield pmap[pid]
except KeyError:
# If we get here it is likely that 2 threads were
# using process_iter().
pass
else:
raise
finally:
_pmap = pmap
def wait_procs(procs, timeout=None, callback=None):
"""Convenience function which waits for a list of processes to
terminate.
Return a (gone, alive) tuple indicating which processes
are gone and which ones are still alive.
The gone ones will have a new *returncode* attribute indicating
process exit status (may be None).
*callback* is a function which gets called every time a process
terminates (a Process instance is passed as callback argument).
Function will return as soon as all processes terminate or when
*timeout* occurs.
Differently from Process.wait() it will not raise TimeoutExpired if
*timeout* occurs.
Typical use case is:
- send SIGTERM to a list of processes
- give them some time to terminate
- send SIGKILL to those ones which are still alive
Example:
>>> def on_terminate(proc):
... print("process {} terminated".format(proc))
...
>>> for p in procs:
... p.terminate()
...
>>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
>>> for p in alive:
... p.kill()
"""
def check_gone(proc, timeout):
try:
returncode = proc.wait(timeout=timeout)
except TimeoutExpired:
pass
except _SubprocessTimeoutExpired:
pass
else:
if returncode is not None or not proc.is_running():
# Set new Process instance attribute.
proc.returncode = returncode
gone.add(proc)
if callback is not None:
callback(proc)
if timeout is not None and not timeout >= 0:
msg = "timeout must be a positive integer, got %s" % timeout
raise ValueError(msg)
gone = set()
alive = set(procs)
if callback is not None and not callable(callback):
raise TypeError("callback %r is not a callable" % callable)
if timeout is not None:
deadline = _timer() + timeout
while alive:
if timeout is not None and timeout <= 0:
break
for proc in alive:
# Make sure that every complete iteration (all processes)
# will last max 1 sec.
# We do this because we don't want to wait too long on a
# single process: in case it terminates too late other
# processes may disappear in the meantime and their PID
# reused.
max_timeout = 1.0 / len(alive)
if timeout is not None:
timeout = min((deadline - _timer()), max_timeout)
if timeout <= 0:
break
check_gone(proc, timeout)
else:
check_gone(proc, max_timeout)
alive = alive - gone
if alive:
# Last attempt over processes survived so far.
# timeout == 0 won't make this function wait any further.
for proc in alive:
check_gone(proc, 0)
alive = alive - gone
return (list(gone), list(alive))
# =====================================================================
# --- CPU related functions
# =====================================================================
def cpu_count(logical=True):
"""Return the number of logical CPUs in the system (same as
os.cpu_count() in Python 3.4).
If *logical* is False return the number of physical cores only
(e.g. hyper thread CPUs are excluded).
Return None if undetermined.
The return value is cached after first call.
If desired cache can be cleared like this:
>>> psutil.cpu_count.cache_clear()
"""
if logical:
ret = _psplatform.cpu_count_logical()
else:
ret = _psplatform.cpu_count_cores()
if ret is not None and ret < 1:
ret = None
return ret
def cpu_times(percpu=False):
"""Return system-wide CPU times as a namedtuple.
Every CPU time represents the seconds the CPU has spent in the
given mode. The namedtuple's fields availability varies depending on the
platform:
- user
- system
- idle
- nice (UNIX)
- iowait (Linux)
- irq (Linux, FreeBSD)
- softirq (Linux)
- steal (Linux >= 2.6.11)
- guest (Linux >= 2.6.24)
- guest_nice (Linux >= 3.2.0)
When *percpu* is True return a list of namedtuples for each CPU.
First element of the list refers to first CPU, second element
to second CPU and so on.
The order of the list is consistent across calls.
"""
if not percpu:
return _psplatform.cpu_times()
else:
return _psplatform.per_cpu_times()
try:
_last_cpu_times = cpu_times()
except Exception:
# Don't want to crash at import time.
_last_cpu_times = None
try:
_last_per_cpu_times = cpu_times(percpu=True)
except Exception:
# Don't want to crash at import time.
_last_per_cpu_times = None
def _cpu_tot_time(times):
"""Given a cpu_time() ntuple calculates the total CPU time
(including idle time).
"""
tot = sum(times)
if LINUX:
# On Linux guest times are already accounted in "user" or
# "nice" times, so we subtract them from total.
# Htop does the same. References:
# https://github.com/giampaolo/psutil/pull/940
# http://unix.stackexchange.com/questions/178045
# https://github.com/torvalds/linux/blob/
# 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
# cputime.c#L158
tot -= getattr(times, "guest", 0) # Linux 2.6.24+
tot -= getattr(times, "guest_nice", 0) # Linux 3.2.0+
return tot
def _cpu_busy_time(times):
"""Given a cpu_time() ntuple calculates the busy CPU time.
We do so by subtracting all idle CPU times.
"""
busy = _cpu_tot_time(times)
busy -= times.idle
# Linux: "iowait" is time during which the CPU does not do anything
# (waits for IO to complete). On Linux IO wait is *not* accounted
# in "idle" time so we subtract it. Htop does the same.
# References:
# https://github.com/torvalds/linux/blob/
# 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
busy -= getattr(times, "iowait", 0)
return busy
def _cpu_times_deltas(t1, t2):
assert t1._fields == t2._fields, (t1, t2)
field_deltas = []
for field in _psplatform.scputimes._fields:
field_delta = getattr(t2, field) - getattr(t1, field)
# CPU times are always supposed to increase over time
# or at least remain the same and that's because time
# cannot go backwards.
# Surprisingly sometimes this might not be the case (at
# least on Windows and Linux), see:
# https://github.com/giampaolo/psutil/issues/392
# https://github.com/giampaolo/psutil/issues/645
# https://github.com/giampaolo/psutil/issues/1210
# Trim negative deltas to zero to ignore decreasing fields.
# top does the same. Reference:
# https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063
field_delta = max(0, field_delta)
field_deltas.append(field_delta)
return _psplatform.scputimes(*field_deltas)
def cpu_percent(interval=None, percpu=False):
"""Return a float representing the current system-wide CPU
utilization as a percentage.
When *interval* is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When *interval* is 0.0 or None compares system CPU times elapsed
since last call or module import, returning immediately (non
blocking). That means the first time this is called it will
return a meaningless 0.0 value which you should ignore.
In this case is recommended for accuracy that this function be
called with at least 0.1 seconds between calls.
When *percpu* is True returns a list of floats representing the
utilization as a percentage for each CPU.
First element of the list refers to first CPU, second element
to second CPU and so on.
The order of the list is consistent across calls.
Examples:
>>> # blocking, system-wide
>>> psutil.cpu_percent(interval=1)
2.0
>>>
>>> # blocking, per-cpu
>>> psutil.cpu_percent(interval=1, percpu=True)
[2.0, 1.0]
>>>
>>> # non-blocking (percentage since last call)
>>> psutil.cpu_percent(interval=None)
2.9
>>>
"""
global _last_cpu_times
global _last_per_cpu_times
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
raise ValueError("interval is not positive (got %r)" % interval)
def calculate(t1, t2):
times_delta = _cpu_times_deltas(t1, t2)
all_delta = _cpu_tot_time(times_delta)
busy_delta = _cpu_busy_time(times_delta)
try:
busy_perc = (busy_delta / all_delta) * 100
except ZeroDivisionError:
return 0.0
else:
return round(busy_perc, 1)
# system-wide usage
if not percpu:
if blocking:
t1 = cpu_times()
time.sleep(interval)
else:
t1 = _last_cpu_times
if t1 is None:
# Something bad happened at import time. We'll
# get a meaningful result on the next call. See:
# https://github.com/giampaolo/psutil/pull/715
t1 = cpu_times()
_last_cpu_times = cpu_times()
return calculate(t1, _last_cpu_times)
# per-cpu usage
else:
ret = []
if blocking:
tot1 = cpu_times(percpu=True)
time.sleep(interval)
else:
tot1 = _last_per_cpu_times
if tot1 is None:
# Something bad happened at import time. We'll
# get a meaningful result on the next call. See:
# https://github.com/giampaolo/psutil/pull/715
tot1 = cpu_times(percpu=True)
_last_per_cpu_times = cpu_times(percpu=True)
for t1, t2 in zip(tot1, _last_per_cpu_times):
ret.append(calculate(t1, t2))
return ret
# Use separate global vars for cpu_times_percent() so that it's
# independent from cpu_percent() and they can both be used within
# the same program.
_last_cpu_times_2 = _last_cpu_times
_last_per_cpu_times_2 = _last_per_cpu_times
def cpu_times_percent(interval=None, percpu=False):
"""Same as cpu_percent() but provides utilization percentages
for each specific CPU time as is returned by cpu_times().
For instance, on Linux we'll get:
>>> cpu_times_percent()
cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
>>>
*interval* and *percpu* arguments have the same meaning as in
cpu_percent().
"""
global _last_cpu_times_2
global _last_per_cpu_times_2
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
raise ValueError("interval is not positive (got %r)" % interval)
def calculate(t1, t2):
nums = []
times_delta = _cpu_times_deltas(t1, t2)
all_delta = _cpu_tot_time(times_delta)
# "scale" is the value to multiply each delta with to get percentages.
# We use "max" to avoid division by zero (if all_delta is 0, then all
# fields are 0 so percentages will be 0 too. all_delta cannot be a
# fraction because cpu times are integers)
scale = 100.0 / max(1, all_delta)
for field_delta in times_delta:
field_perc = field_delta * scale
field_perc = round(field_perc, 1)
# make sure we don't return negative values or values over 100%
field_perc = min(max(0.0, field_perc), 100.0)
nums.append(field_perc)
return _psplatform.scputimes(*nums)
# system-wide usage
if not percpu:
if blocking:
t1 = cpu_times()
time.sleep(interval)
else:
t1 = _last_cpu_times_2
if t1 is None:
# Something bad happened at import time. We'll
# get a meaningful result on the next call. See:
# https://github.com/giampaolo/psutil/pull/715
t1 = cpu_times()
_last_cpu_times_2 = cpu_times()
return calculate(t1, _last_cpu_times_2)
# per-cpu usage
else:
ret = []
if blocking:
tot1 = cpu_times(percpu=True)
time.sleep(interval)
else:
tot1 = _last_per_cpu_times_2
if tot1 is None:
# Something bad happened at import time. We'll
# get a meaningful result on the next call. See:
# https://github.com/giampaolo/psutil/pull/715
tot1 = cpu_times(percpu=True)
_last_per_cpu_times_2 = cpu_times(percpu=True)
for t1, t2 in zip(tot1, _last_per_cpu_times_2):
ret.append(calculate(t1, t2))
return ret
def cpu_stats():
"""Return CPU statistics."""
return _psplatform.cpu_stats()
if hasattr(_psplatform, "cpu_freq"):
def cpu_freq(percpu=False):
"""Return CPU frequency as a namedtuple including current,
min and max frequency expressed in Mhz.
If *percpu* is True and the system supports per-cpu frequency
retrieval (Linux only) a list of frequencies is returned for
each CPU. If not a list with one element is returned.
"""
ret = _psplatform.cpu_freq()
if percpu:
return ret
else:
num_cpus = float(len(ret))
if num_cpus == 0:
return None
elif num_cpus == 1:
return ret[0]
else:
currs, mins, maxs = 0.0, 0.0, 0.0
set_none = False
for cpu in ret:
currs += cpu.current
# On Linux if /proc/cpuinfo is used min/max are set
# to None.
if LINUX and cpu.min is None:
set_none = True
continue
mins += cpu.min
maxs += cpu.max
current = currs / num_cpus
if set_none:
min_ = max_ = None
else:
min_ = mins / num_cpus
max_ = maxs / num_cpus
return _common.scpufreq(current, min_, max_)
__all__.append("cpu_freq")
if hasattr(os, "getloadavg") or hasattr(_psplatform, "getloadavg"):
# Perform this hasattr check once on import time to either use the
# platform based code or proxy straight from the os module.
if hasattr(os, "getloadavg"):
getloadavg = os.getloadavg
else:
getloadavg = _psplatform.getloadavg
__all__.append("getloadavg")
# =====================================================================
# --- system memory related functions
# =====================================================================
def virtual_memory():
"""Return statistics about system memory usage as a namedtuple
including the following fields, expressed in bytes:
- total:
total physical memory available.
- available:
the memory that can be given instantly to processes without the
system going into swap.
This is calculated by summing different memory values depending
on the platform and it is supposed to be used to monitor actual
memory usage in a cross platform fashion.
- percent:
the percentage usage calculated as (total - available) / total * 100
- used:
memory used, calculated differently depending on the platform and
designed for informational purposes only:
macOS: active + wired
BSD: active + wired + cached
Linux: total - free
- free:
memory not being used at all (zeroed) that is readily available;
note that this doesn't reflect the actual memory available
(use 'available' instead)
Platform-specific fields:
- active (UNIX):
memory currently in use or very recently used, and so it is in RAM.
- inactive (UNIX):
memory that is marked as not used.
- buffers (BSD, Linux):
cache for things like file system metadata.
- cached (BSD, macOS):
cache for various things.
- wired (macOS, BSD):
memory that is marked to always stay in RAM. It is never moved to disk.
- shared (BSD):
memory that may be simultaneously accessed by multiple processes.
The sum of 'used' and 'available' does not necessarily equal total.
On Windows 'available' and 'free' are the same.
"""
global _TOTAL_PHYMEM
ret = _psplatform.virtual_memory()
# cached for later use in Process.memory_percent()
_TOTAL_PHYMEM = ret.total
return ret
def swap_memory():
"""Return system swap memory statistics as a namedtuple including
the following fields:
- total: total swap memory in bytes
- used: used swap memory in bytes
- free: free swap memory in bytes
- percent: the percentage usage
- sin: no. of bytes the system has swapped in from disk (cumulative)
- sout: no. of bytes the system has swapped out from disk (cumulative)
'sin' and 'sout' on Windows are meaningless and always set to 0.
"""
return _psplatform.swap_memory()
# =====================================================================
# --- disks/paritions related functions
# =====================================================================
def disk_usage(path):
"""Return disk usage statistics about the given *path* as a
namedtuple including total, used and free space expressed in bytes
plus the percentage usage.
"""
return _psplatform.disk_usage(path)
def disk_partitions(all=False):
"""Return mounted partitions as a list of
(device, mountpoint, fstype, opts) namedtuple.
'opts' field is a raw string separated by commas indicating mount
options which may vary depending on the platform.
If *all* parameter is False return physical devices only and ignore
all others.
"""
def pathconf(path, name):
try:
return os.pathconf(path, name)
except (OSError, AttributeError):
pass
ret = _psplatform.disk_partitions(all)
if POSIX:
new = []
for item in ret:
nt = item._replace(
maxfile=pathconf(item.mountpoint, 'PC_NAME_MAX'),
maxpath=pathconf(item.mountpoint, 'PC_PATH_MAX'))
new.append(nt)
return new
else:
return ret
def disk_io_counters(perdisk=False, nowrap=True):
"""Return system disk I/O statistics as a namedtuple including
the following fields:
- read_count: number of reads
- write_count: number of writes
- read_bytes: number of bytes read
- write_bytes: number of bytes written
- read_time: time spent reading from disk (in ms)
- write_time: time spent writing to disk (in ms)
Platform specific:
- busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
- read_merged_count (Linux): number of merged reads
- write_merged_count (Linux): number of merged writes
If *perdisk* is True return the same information for every
physical disk installed on the system as a dictionary
with partition names as the keys and the namedtuple
described above as the values.
If *nowrap* is True it detects and adjust the numbers which overflow
and wrap (restart from 0) and add "old value" to "new value" so that
the returned numbers will always be increasing or remain the same,
but never decrease.
"disk_io_counters.cache_clear()" can be used to invalidate the
cache.
On recent Windows versions 'diskperf -y' command may need to be
executed first otherwise this function won't find any disk.
"""
kwargs = dict(perdisk=perdisk) if LINUX else {}
rawdict = _psplatform.disk_io_counters(**kwargs)
if not rawdict:
return {} if perdisk else None
if nowrap:
rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters')
nt = getattr(_psplatform, "sdiskio", _common.sdiskio)
if perdisk:
for disk, fields in rawdict.items():
rawdict[disk] = nt(*fields)
return rawdict
else:
return nt(*(sum(x) for x in zip(*rawdict.values())))
disk_io_counters.cache_clear = functools.partial(
_wrap_numbers.cache_clear, 'psutil.disk_io_counters')
disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
# =====================================================================
# --- network related functions
# =====================================================================
def net_io_counters(pernic=False, nowrap=True):
"""Return network I/O statistics as a namedtuple including
the following fields:
- bytes_sent: number of bytes sent
- bytes_recv: number of bytes received
- packets_sent: number of packets sent
- packets_recv: number of packets received
- errin: total number of errors while receiving
- errout: total number of errors while sending
- dropin: total number of incoming packets which were dropped
- dropout: total number of outgoing packets which were dropped
(always 0 on macOS and BSD)
If *pernic* is True return the same information for every
network interface installed on the system as a dictionary
with network interface names as the keys and the namedtuple
described above as the values.
If *nowrap* is True it detects and adjust the numbers which overflow
and wrap (restart from 0) and add "old value" to "new value" so that
the returned numbers will always be increasing or remain the same,
but never decrease.
"disk_io_counters.cache_clear()" can be used to invalidate the
cache.
"""
rawdict = _psplatform.net_io_counters()
if not rawdict:
return {} if pernic else None
if nowrap:
rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters')
if pernic:
for nic, fields in rawdict.items():
rawdict[nic] = _common.snetio(*fields)
return rawdict
else:
return _common.snetio(*[sum(x) for x in zip(*rawdict.values())])
net_io_counters.cache_clear = functools.partial(
_wrap_numbers.cache_clear, 'psutil.net_io_counters')
net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
def net_connections(kind='inet'):
"""Return system-wide socket connections as a list of
(fd, family, type, laddr, raddr, status, pid) namedtuples.
In case of limited privileges 'fd' and 'pid' may be set to -1
and None respectively.
The *kind* parameter filters for connections that fit the
following criteria:
+------------+----------------------------------------------------+
| Kind Value | Connections using |
+------------+----------------------------------------------------+
| inet | IPv4 and IPv6 |
| inet4 | IPv4 |
| inet6 | IPv6 |
| tcp | TCP |
| tcp4 | TCP over IPv4 |
| tcp6 | TCP over IPv6 |
| udp | UDP |
| udp4 | UDP over IPv4 |
| udp6 | UDP over IPv6 |
| unix | UNIX socket (both UDP and TCP protocols) |
| all | the sum of all the possible families and protocols |
+------------+----------------------------------------------------+
On macOS this function requires root privileges.
"""
return _psplatform.net_connections(kind)
def net_if_addrs():
"""Return the addresses associated to each NIC (network interface
card) installed on the system as a dictionary whose keys are the
NIC names and value is a list of namedtuples for each address
assigned to the NIC. Each namedtuple includes 5 fields:
- family: can be either socket.AF_INET, socket.AF_INET6 or
psutil.AF_LINK, which refers to a MAC address.
- address: is the primary address and it is always set.
- netmask: and 'broadcast' and 'ptp' may be None.
- ptp: stands for "point to point" and references the
destination address on a point to point interface
(typically a VPN).
- broadcast: and *ptp* are mutually exclusive.
Note: you can have more than one address of the same family
associated with each interface.
"""
has_enums = sys.version_info >= (3, 4)
if has_enums:
import socket
rawlist = _psplatform.net_if_addrs()
rawlist.sort(key=lambda x: x[1]) # sort by family
ret = collections.defaultdict(list)
for name, fam, addr, mask, broadcast, ptp in rawlist:
if has_enums:
try:
fam = socket.AddressFamily(fam)
except ValueError:
if WINDOWS and fam == -1:
fam = _psplatform.AF_LINK
elif (hasattr(_psplatform, "AF_LINK") and
_psplatform.AF_LINK == fam):
# Linux defines AF_LINK as an alias for AF_PACKET.
# We re-set the family here so that repr(family)
# will show AF_LINK rather than AF_PACKET
fam = _psplatform.AF_LINK
if fam == _psplatform.AF_LINK:
# The underlying C function may return an incomplete MAC
# address in which case we fill it with null bytes, see:
# https://github.com/giampaolo/psutil/issues/786
separator = ":" if POSIX else "-"
while addr.count(separator) < 5:
addr += "%s00" % separator
ret[name].append(_common.snicaddr(fam, addr, mask, broadcast, ptp))
return dict(ret)
def net_if_stats():
"""Return information about each NIC (network interface card)
installed on the system as a dictionary whose keys are the
NIC names and value is a namedtuple with the following fields:
- isup: whether the interface is up (bool)
- duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
NIC_DUPLEX_UNKNOWN
- speed: the NIC speed expressed in mega bits (MB); if it can't
be determined (e.g. 'localhost') it will be set to 0.
- mtu: the maximum transmission unit expressed in bytes.
"""
return _psplatform.net_if_stats()
# =====================================================================
# --- sensors
# =====================================================================
# Linux, macOS
if hasattr(_psplatform, "sensors_temperatures"):
def sensors_temperatures(fahrenheit=False):
"""Return hardware temperatures. Each entry is a namedtuple
representing a certain hardware sensor (it may be a CPU, an
hard disk or something else, depending on the OS and its
configuration).
All temperatures are expressed in celsius unless *fahrenheit*
is set to True.
"""
def convert(n):
if n is not None:
return (float(n) * 9 / 5) + 32 if fahrenheit else n
ret = collections.defaultdict(list)
rawdict = _psplatform.sensors_temperatures()
for name, values in rawdict.items():
while values:
label, current, high, critical = values.pop(0)
current = convert(current)
high = convert(high)
critical = convert(critical)
if high and not critical:
critical = high
elif critical and not high:
high = critical
ret[name].append(
_common.shwtemp(label, current, high, critical))
return dict(ret)
__all__.append("sensors_temperatures")
# Linux
if hasattr(_psplatform, "sensors_fans"):
def sensors_fans():
"""Return fans speed. Each entry is a namedtuple
representing a certain hardware sensor.
All speed are expressed in RPM (rounds per minute).
"""
return _psplatform.sensors_fans()
__all__.append("sensors_fans")
# Linux, Windows, FreeBSD, macOS
if hasattr(_psplatform, "sensors_battery"):
def sensors_battery():
"""Return battery information. If no battery is installed
returns None.
- percent: battery power left as a percentage.
- secsleft: a rough approximation of how many seconds are left
before the battery runs out of power. May be
POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
- power_plugged: True if the AC power cable is connected.
"""
return _psplatform.sensors_battery()
__all__.append("sensors_battery")
# =====================================================================
# --- other system related functions
# =====================================================================
def boot_time():
"""Return the system boot time expressed in seconds since the epoch."""
# Note: we are not caching this because it is subject to
# system clock updates.
return _psplatform.boot_time()
def users():
"""Return users currently connected on the system as a list of
namedtuples including the following fields.
- user: the name of the user
- terminal: the tty or pseudo-tty associated with the user, if any.
- host: the host name associated with the entry, if any.
- started: the creation time as a floating point number expressed in
seconds since the epoch.
"""
return _psplatform.users()
# =====================================================================
# --- Windows services
# =====================================================================
if WINDOWS:
def win_service_iter():
"""Return a generator yielding a WindowsService instance for all
Windows services installed.
"""
return _psplatform.win_service_iter()
def win_service_get(name):
"""Get a Windows service by *name*.
Raise NoSuchProcess if no service with such name exists.
"""
return _psplatform.win_service_get(name)
# =====================================================================
def _set_debug(value):
"""Enable or disable PSUTIL_DEBUG option, which prints debugging
messages to stderr.
"""
import psutil._common
psutil._common.PSUTIL_DEBUG = bool(value)
_psplatform.cext.set_debug(bool(value))
def test(): # pragma: no cover
from ._common import bytes2human
from ._compat import get_terminal_size
today_day = datetime.date.today()
templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s"
attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times',
'create_time', 'memory_info', 'status', 'nice', 'username']
print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE", # NOQA
"STATUS", "START", "TIME", "CMDLINE"))
for p in process_iter(attrs, ad_value=None):
if p.info['create_time']:
ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
if ctime.date() == today_day:
ctime = ctime.strftime("%H:%M")
else:
ctime = ctime.strftime("%b%d")
else:
ctime = ''
if p.info['cpu_times']:
cputime = time.strftime("%M:%S",
time.localtime(sum(p.info['cpu_times'])))
else:
cputime = ''
user = p.info['username'] or ''
if not user and POSIX:
try:
user = p.uids()[0]
except Error:
pass
if user and WINDOWS and '\\' in user:
user = user.split('\\')[1]
user = user[:9]
vms = bytes2human(p.info['memory_info'].vms) if \
p.info['memory_info'] is not None else ''
rss = bytes2human(p.info['memory_info'].rss) if \
p.info['memory_info'] is not None else ''
memp = round(p.info['memory_percent'], 1) if \
p.info['memory_percent'] is not None else ''
nice = int(p.info['nice']) if p.info['nice'] else ''
if p.info['cmdline']:
cmdline = ' '.join(p.info['cmdline'])
else:
cmdline = p.info['name']
status = p.info['status'][:5] if p.info['status'] else ''
line = templ % (
user[:10],
p.info['pid'],
memp,
vms,
rss,
nice,
status,
ctime,
cputime,
cmdline)
print(line[:get_terminal_size()[0]]) # NOQA
del memoize_when_activated, division
if sys.version_info[0] < 3:
del num, x
if __name__ == "__main__":
test()
| 87,870 | 35.086653 | 79 | py |
psutil | psutil-master/psutil/_common.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Common objects shared by __init__.py and _ps*.py modules."""
# Note: this module is imported by setup.py so it should not import
# psutil or third-party modules.
from __future__ import division
from __future__ import print_function
import collections
import contextlib
import errno
import functools
import os
import socket
import stat
import sys
import threading
import warnings
from collections import namedtuple
from socket import AF_INET
from socket import SOCK_DGRAM
from socket import SOCK_STREAM
try:
from socket import AF_INET6
except ImportError:
AF_INET6 = None
try:
from socket import AF_UNIX
except ImportError:
AF_UNIX = None
if sys.version_info >= (3, 4):
import enum
else:
enum = None
# can't take it from _common.py as this script is imported by setup.py
PY3 = sys.version_info[0] == 3
PSUTIL_DEBUG = bool(os.getenv('PSUTIL_DEBUG'))
_DEFAULT = object()
__all__ = [
# OS constants
'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'MACOS', 'OSX', 'POSIX',
'SUNOS', 'WINDOWS',
# connection constants
'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED',
'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN',
'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT',
# net constants
'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN',
# process status constants
'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED',
'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED',
'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL',
'STATUS_WAKING', 'STATUS_ZOMBIE', 'STATUS_PARKED',
# other constants
'ENCODING', 'ENCODING_ERRS', 'AF_INET6',
# named tuples
'pconn', 'pcputimes', 'pctxsw', 'pgids', 'pio', 'pionice', 'popenfile',
'pthread', 'puids', 'sconn', 'scpustats', 'sdiskio', 'sdiskpart',
'sdiskusage', 'snetio', 'snicaddr', 'snicstats', 'sswap', 'suser',
# utility functions
'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize',
'parse_environ_block', 'path_exists_strict', 'usage_percent',
'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers",
'open_text', 'open_binary', 'cat', 'bcat',
'bytes2human', 'conn_to_ntuple', 'debug',
# shell utils
'hilite', 'term_supports_colors', 'print_color',
]
# ===================================================================
# --- OS constants
# ===================================================================
POSIX = os.name == "posix"
WINDOWS = os.name == "nt"
LINUX = sys.platform.startswith("linux")
MACOS = sys.platform.startswith("darwin")
OSX = MACOS # deprecated alias
FREEBSD = sys.platform.startswith(("freebsd", "midnightbsd"))
OPENBSD = sys.platform.startswith("openbsd")
NETBSD = sys.platform.startswith("netbsd")
BSD = FREEBSD or OPENBSD or NETBSD
SUNOS = sys.platform.startswith(("sunos", "solaris"))
AIX = sys.platform.startswith("aix")
# ===================================================================
# --- API constants
# ===================================================================
# Process.status()
STATUS_RUNNING = "running"
STATUS_SLEEPING = "sleeping"
STATUS_DISK_SLEEP = "disk-sleep"
STATUS_STOPPED = "stopped"
STATUS_TRACING_STOP = "tracing-stop"
STATUS_ZOMBIE = "zombie"
STATUS_DEAD = "dead"
STATUS_WAKE_KILL = "wake-kill"
STATUS_WAKING = "waking"
STATUS_IDLE = "idle" # Linux, macOS, FreeBSD
STATUS_LOCKED = "locked" # FreeBSD
STATUS_WAITING = "waiting" # FreeBSD
STATUS_SUSPENDED = "suspended" # NetBSD
STATUS_PARKED = "parked" # Linux
# Process.connections() and psutil.net_connections()
CONN_ESTABLISHED = "ESTABLISHED"
CONN_SYN_SENT = "SYN_SENT"
CONN_SYN_RECV = "SYN_RECV"
CONN_FIN_WAIT1 = "FIN_WAIT1"
CONN_FIN_WAIT2 = "FIN_WAIT2"
CONN_TIME_WAIT = "TIME_WAIT"
CONN_CLOSE = "CLOSE"
CONN_CLOSE_WAIT = "CLOSE_WAIT"
CONN_LAST_ACK = "LAST_ACK"
CONN_LISTEN = "LISTEN"
CONN_CLOSING = "CLOSING"
CONN_NONE = "NONE"
# net_if_stats()
if enum is None:
NIC_DUPLEX_FULL = 2
NIC_DUPLEX_HALF = 1
NIC_DUPLEX_UNKNOWN = 0
else:
class NicDuplex(enum.IntEnum):
NIC_DUPLEX_FULL = 2
NIC_DUPLEX_HALF = 1
NIC_DUPLEX_UNKNOWN = 0
globals().update(NicDuplex.__members__)
# sensors_battery()
if enum is None:
POWER_TIME_UNKNOWN = -1
POWER_TIME_UNLIMITED = -2
else:
class BatteryTime(enum.IntEnum):
POWER_TIME_UNKNOWN = -1
POWER_TIME_UNLIMITED = -2
globals().update(BatteryTime.__members__)
# --- others
ENCODING = sys.getfilesystemencoding()
if not PY3:
ENCODING_ERRS = "replace"
else:
try:
ENCODING_ERRS = sys.getfilesystemencodeerrors() # py 3.6
except AttributeError:
ENCODING_ERRS = "surrogateescape" if POSIX else "replace"
# ===================================================================
# --- namedtuples
# ===================================================================
# --- for system functions
# psutil.swap_memory()
sswap = namedtuple('sswap', ['total', 'used', 'free', 'percent', 'sin',
'sout'])
# psutil.disk_usage()
sdiskusage = namedtuple('sdiskusage', ['total', 'used', 'free', 'percent'])
# psutil.disk_io_counters()
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
'read_bytes', 'write_bytes',
'read_time', 'write_time'])
# psutil.disk_partitions()
sdiskpart = namedtuple('sdiskpart', ['device', 'mountpoint', 'fstype', 'opts',
'maxfile', 'maxpath'])
# psutil.net_io_counters()
snetio = namedtuple('snetio', ['bytes_sent', 'bytes_recv',
'packets_sent', 'packets_recv',
'errin', 'errout',
'dropin', 'dropout'])
# psutil.users()
suser = namedtuple('suser', ['name', 'terminal', 'host', 'started', 'pid'])
# psutil.net_connections()
sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr',
'status', 'pid'])
# psutil.net_if_addrs()
snicaddr = namedtuple('snicaddr',
['family', 'address', 'netmask', 'broadcast', 'ptp'])
# psutil.net_if_stats()
snicstats = namedtuple('snicstats',
['isup', 'duplex', 'speed', 'mtu', 'flags'])
# psutil.cpu_stats()
scpustats = namedtuple(
'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'])
# psutil.cpu_freq()
scpufreq = namedtuple('scpufreq', ['current', 'min', 'max'])
# psutil.sensors_temperatures()
shwtemp = namedtuple(
'shwtemp', ['label', 'current', 'high', 'critical'])
# psutil.sensors_battery()
sbattery = namedtuple('sbattery', ['percent', 'secsleft', 'power_plugged'])
# psutil.sensors_fans()
sfan = namedtuple('sfan', ['label', 'current'])
# --- for Process methods
# psutil.Process.cpu_times()
pcputimes = namedtuple('pcputimes',
['user', 'system', 'children_user', 'children_system'])
# psutil.Process.open_files()
popenfile = namedtuple('popenfile', ['path', 'fd'])
# psutil.Process.threads()
pthread = namedtuple('pthread', ['id', 'user_time', 'system_time'])
# psutil.Process.uids()
puids = namedtuple('puids', ['real', 'effective', 'saved'])
# psutil.Process.gids()
pgids = namedtuple('pgids', ['real', 'effective', 'saved'])
# psutil.Process.io_counters()
pio = namedtuple('pio', ['read_count', 'write_count',
'read_bytes', 'write_bytes'])
# psutil.Process.ionice()
pionice = namedtuple('pionice', ['ioclass', 'value'])
# psutil.Process.ctx_switches()
pctxsw = namedtuple('pctxsw', ['voluntary', 'involuntary'])
# psutil.Process.connections()
pconn = namedtuple('pconn', ['fd', 'family', 'type', 'laddr', 'raddr',
'status'])
# psutil.connections() and psutil.Process.connections()
addr = namedtuple('addr', ['ip', 'port'])
# ===================================================================
# --- Process.connections() 'kind' parameter mapping
# ===================================================================
conn_tmap = {
"all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
"tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]),
"tcp4": ([AF_INET], [SOCK_STREAM]),
"udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]),
"udp4": ([AF_INET], [SOCK_DGRAM]),
"inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
"inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]),
"inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
}
if AF_INET6 is not None:
conn_tmap.update({
"tcp6": ([AF_INET6], [SOCK_STREAM]),
"udp6": ([AF_INET6], [SOCK_DGRAM]),
})
if AF_UNIX is not None:
conn_tmap.update({
"unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
})
# =====================================================================
# --- Exceptions
# =====================================================================
class Error(Exception):
"""Base exception class. All other psutil exceptions inherit
from this one.
"""
__module__ = 'psutil'
def _infodict(self, attrs):
info = collections.OrderedDict()
for name in attrs:
value = getattr(self, name, None)
if value:
info[name] = value
elif name == "pid" and value == 0:
info[name] = value
return info
def __str__(self):
# invoked on `raise Error`
info = self._infodict(("pid", "ppid", "name"))
if info:
details = "(%s)" % ", ".join(
["%s=%r" % (k, v) for k, v in info.items()])
else:
details = None
return " ".join([x for x in (getattr(self, "msg", ""), details) if x])
def __repr__(self):
# invoked on `repr(Error)`
info = self._infodict(("pid", "ppid", "name", "seconds", "msg"))
details = ", ".join(["%s=%r" % (k, v) for k, v in info.items()])
return "psutil.%s(%s)" % (self.__class__.__name__, details)
class NoSuchProcess(Error):
"""Exception raised when a process with a certain PID doesn't
or no longer exists.
"""
__module__ = 'psutil'
def __init__(self, pid, name=None, msg=None):
Error.__init__(self)
self.pid = pid
self.name = name
self.msg = msg or "process no longer exists"
class ZombieProcess(NoSuchProcess):
"""Exception raised when querying a zombie process. This is
raised on macOS, BSD and Solaris only, and not always: depending
on the query the OS may be able to succeed anyway.
On Linux all zombie processes are querable (hence this is never
raised). Windows doesn't have zombie processes.
"""
__module__ = 'psutil'
def __init__(self, pid, name=None, ppid=None, msg=None):
NoSuchProcess.__init__(self, pid, name, msg)
self.ppid = ppid
self.msg = msg or "PID still exists but it's a zombie"
class AccessDenied(Error):
"""Exception raised when permission to perform an action is denied."""
__module__ = 'psutil'
def __init__(self, pid=None, name=None, msg=None):
Error.__init__(self)
self.pid = pid
self.name = name
self.msg = msg or ""
class TimeoutExpired(Error):
"""Raised on Process.wait(timeout) if timeout expires and process
is still alive.
"""
__module__ = 'psutil'
def __init__(self, seconds, pid=None, name=None):
Error.__init__(self)
self.seconds = seconds
self.pid = pid
self.name = name
self.msg = "timeout after %s seconds" % seconds
# ===================================================================
# --- utils
# ===================================================================
# This should be in _compat.py rather than here, but does not work well
# with setup.py importing this module via a sys.path trick.
if PY3:
if isinstance(__builtins__, dict): # cpython
exec_ = __builtins__["exec"]
else: # pypy
exec_ = getattr(__builtins__, "exec") # noqa
exec_("""def raise_from(value, from_value):
try:
raise value from from_value
finally:
value = None
""")
else:
def raise_from(value, from_value):
raise value
def usage_percent(used, total, round_=None):
"""Calculate percentage usage of 'used' against 'total'."""
try:
ret = (float(used) / total) * 100
except ZeroDivisionError:
return 0.0
else:
if round_ is not None:
ret = round(ret, round_)
return ret
def memoize(fun):
"""A simple memoize decorator for functions supporting (hashable)
positional arguments.
It also provides a cache_clear() function for clearing the cache:
>>> @memoize
... def foo()
... return 1
...
>>> foo()
1
>>> foo.cache_clear()
>>>
It supports:
- functions
- classes (acts as a @singleton)
- staticmethods
- classmethods
It does NOT support:
- methods
"""
@functools.wraps(fun)
def wrapper(*args, **kwargs):
key = (args, frozenset(sorted(kwargs.items())))
try:
return cache[key]
except KeyError:
try:
ret = cache[key] = fun(*args, **kwargs)
except Exception as err:
raise raise_from(err, None)
return ret
def cache_clear():
"""Clear cache."""
cache.clear()
cache = {}
wrapper.cache_clear = cache_clear
return wrapper
def memoize_when_activated(fun):
"""A memoize decorator which is disabled by default. It can be
activated and deactivated on request.
For efficiency reasons it can be used only against class methods
accepting no arguments.
>>> class Foo:
... @memoize
... def foo()
... print(1)
...
>>> f = Foo()
>>> # deactivated (default)
>>> foo()
1
>>> foo()
1
>>>
>>> # activated
>>> foo.cache_activate(self)
>>> foo()
1
>>> foo()
>>> foo()
>>>
"""
@functools.wraps(fun)
def wrapper(self):
try:
# case 1: we previously entered oneshot() ctx
ret = self._cache[fun]
except AttributeError:
# case 2: we never entered oneshot() ctx
try:
return fun(self)
except Exception as err:
raise raise_from(err, None)
except KeyError:
# case 3: we entered oneshot() ctx but there's no cache
# for this entry yet
try:
ret = fun(self)
except Exception as err:
raise raise_from(err, None)
try:
self._cache[fun] = ret
except AttributeError:
# multi-threading race condition, see:
# https://github.com/giampaolo/psutil/issues/1948
pass
return ret
def cache_activate(proc):
"""Activate cache. Expects a Process instance. Cache will be
stored as a "_cache" instance attribute."""
proc._cache = {}
def cache_deactivate(proc):
"""Deactivate and clear cache."""
try:
del proc._cache
except AttributeError:
pass
wrapper.cache_activate = cache_activate
wrapper.cache_deactivate = cache_deactivate
return wrapper
def isfile_strict(path):
"""Same as os.path.isfile() but does not swallow EACCES / EPERM
exceptions, see:
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
"""
try:
st = os.stat(path)
except OSError as err:
if err.errno in (errno.EPERM, errno.EACCES):
raise
return False
else:
return stat.S_ISREG(st.st_mode)
def path_exists_strict(path):
"""Same as os.path.exists() but does not swallow EACCES / EPERM
exceptions, see:
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
"""
try:
os.stat(path)
except OSError as err:
if err.errno in (errno.EPERM, errno.EACCES):
raise
return False
else:
return True
@memoize
def supports_ipv6():
"""Return True if IPv6 is supported on this platform."""
if not socket.has_ipv6 or AF_INET6 is None:
return False
try:
sock = socket.socket(AF_INET6, socket.SOCK_STREAM)
with contextlib.closing(sock):
sock.bind(("::1", 0))
return True
except socket.error:
return False
def parse_environ_block(data):
"""Parse a C environ block of environment variables into a dictionary."""
# The block is usually raw data from the target process. It might contain
# trailing garbage and lines that do not look like assignments.
ret = {}
pos = 0
# localize global variable to speed up access.
WINDOWS_ = WINDOWS
while True:
next_pos = data.find("\0", pos)
# nul byte at the beginning or double nul byte means finish
if next_pos <= pos:
break
# there might not be an equals sign
equal_pos = data.find("=", pos, next_pos)
if equal_pos > pos:
key = data[pos:equal_pos]
value = data[equal_pos + 1:next_pos]
# Windows expects environment variables to be uppercase only
if WINDOWS_:
key = key.upper()
ret[key] = value
pos = next_pos + 1
return ret
def sockfam_to_enum(num):
"""Convert a numeric socket family value to an IntEnum member.
If it's not a known member, return the numeric value itself.
"""
if enum is None:
return num
else: # pragma: no cover
try:
return socket.AddressFamily(num)
except ValueError:
return num
def socktype_to_enum(num):
"""Convert a numeric socket type value to an IntEnum member.
If it's not a known member, return the numeric value itself.
"""
if enum is None:
return num
else: # pragma: no cover
try:
return socket.SocketKind(num)
except ValueError:
return num
def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None):
"""Convert a raw connection tuple to a proper ntuple."""
if fam in (socket.AF_INET, AF_INET6):
if laddr:
laddr = addr(*laddr)
if raddr:
raddr = addr(*raddr)
if type_ == socket.SOCK_STREAM and fam in (AF_INET, AF_INET6):
status = status_map.get(status, CONN_NONE)
else:
status = CONN_NONE # ignore whatever C returned to us
fam = sockfam_to_enum(fam)
type_ = socktype_to_enum(type_)
if pid is None:
return pconn(fd, fam, type_, laddr, raddr, status)
else:
return sconn(fd, fam, type_, laddr, raddr, status, pid)
def deprecated_method(replacement):
"""A decorator which can be used to mark a method as deprecated
'replcement' is the method name which will be called instead.
"""
def outer(fun):
msg = "%s() is deprecated and will be removed; use %s() instead" % (
fun.__name__, replacement)
if fun.__doc__ is None:
fun.__doc__ = msg
@functools.wraps(fun)
def inner(self, *args, **kwargs):
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return getattr(self, replacement)(*args, **kwargs)
return inner
return outer
class _WrapNumbers:
"""Watches numbers so that they don't overflow and wrap
(reset to zero).
"""
def __init__(self):
self.lock = threading.Lock()
self.cache = {}
self.reminders = {}
self.reminder_keys = {}
def _add_dict(self, input_dict, name):
assert name not in self.cache
assert name not in self.reminders
assert name not in self.reminder_keys
self.cache[name] = input_dict
self.reminders[name] = collections.defaultdict(int)
self.reminder_keys[name] = collections.defaultdict(set)
def _remove_dead_reminders(self, input_dict, name):
"""In case the number of keys changed between calls (e.g. a
disk disappears) this removes the entry from self.reminders.
"""
old_dict = self.cache[name]
gone_keys = set(old_dict.keys()) - set(input_dict.keys())
for gone_key in gone_keys:
for remkey in self.reminder_keys[name][gone_key]:
del self.reminders[name][remkey]
del self.reminder_keys[name][gone_key]
def run(self, input_dict, name):
"""Cache dict and sum numbers which overflow and wrap.
Return an updated copy of `input_dict`
"""
if name not in self.cache:
# This was the first call.
self._add_dict(input_dict, name)
return input_dict
self._remove_dead_reminders(input_dict, name)
old_dict = self.cache[name]
new_dict = {}
for key in input_dict.keys():
input_tuple = input_dict[key]
try:
old_tuple = old_dict[key]
except KeyError:
# The input dict has a new key (e.g. a new disk or NIC)
# which didn't exist in the previous call.
new_dict[key] = input_tuple
continue
bits = []
for i in range(len(input_tuple)):
input_value = input_tuple[i]
old_value = old_tuple[i]
remkey = (key, i)
if input_value < old_value:
# it wrapped!
self.reminders[name][remkey] += old_value
self.reminder_keys[name][key].add(remkey)
bits.append(input_value + self.reminders[name][remkey])
new_dict[key] = tuple(bits)
self.cache[name] = input_dict
return new_dict
def cache_clear(self, name=None):
"""Clear the internal cache, optionally only for function 'name'."""
with self.lock:
if name is None:
self.cache.clear()
self.reminders.clear()
self.reminder_keys.clear()
else:
self.cache.pop(name, None)
self.reminders.pop(name, None)
self.reminder_keys.pop(name, None)
def cache_info(self):
"""Return internal cache dicts as a tuple of 3 elements."""
with self.lock:
return (self.cache, self.reminders, self.reminder_keys)
def wrap_numbers(input_dict, name):
"""Given an `input_dict` and a function `name`, adjust the numbers
which "wrap" (restart from zero) across different calls by adding
"old value" to "new value" and return an updated dict.
"""
with _wn.lock:
return _wn.run(input_dict, name)
_wn = _WrapNumbers()
wrap_numbers.cache_clear = _wn.cache_clear
wrap_numbers.cache_info = _wn.cache_info
# The read buffer size for open() builtin. This (also) dictates how
# much data we read(2) when iterating over file lines as in:
# >>> with open(file) as f:
# ... for line in f:
# ... ...
# Default per-line buffer size for binary files is 1K. For text files
# is 8K. We use a bigger buffer (32K) in order to have more consistent
# results when reading /proc pseudo files on Linux, see:
# https://github.com/giampaolo/psutil/issues/2050
# On Python 2 this also speeds up the reading of big files:
# (namely /proc/{pid}/smaps and /proc/net/*):
# https://github.com/giampaolo/psutil/issues/708
FILE_READ_BUFFER_SIZE = 32 * 1024
def open_binary(fname):
return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE)
def open_text(fname):
"""On Python 3 opens a file in text mode by using fs encoding and
a proper en/decoding errors handler.
On Python 2 this is just an alias for open(name, 'rt').
"""
if not PY3:
return open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE)
# See:
# https://github.com/giampaolo/psutil/issues/675
# https://github.com/giampaolo/psutil/pull/733
fobj = open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE,
encoding=ENCODING, errors=ENCODING_ERRS)
try:
# Dictates per-line read(2) buffer size. Defaults is 8k. See:
# https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546
fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE
except AttributeError:
pass
except Exception:
fobj.close()
raise
return fobj
def cat(fname, fallback=_DEFAULT, _open=open_text):
"""Read entire file content and return it as a string. File is
opened in text mode. If specified, `fallback` is the value
returned in case of error, either if the file does not exist or
it can't be read().
"""
if fallback is _DEFAULT:
with _open(fname) as f:
return f.read()
else:
try:
with _open(fname) as f:
return f.read()
except (IOError, OSError):
return fallback
def bcat(fname, fallback=_DEFAULT):
"""Same as above but opens file in binary mode."""
return cat(fname, fallback=fallback, _open=open_binary)
def bytes2human(n, format="%(value).1f%(symbol)s"):
"""Used by various scripts. See:
http://goo.gl/zeJZl
>>> bytes2human(10000)
'9.8K'
>>> bytes2human(100001221)
'95.4M'
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i + 1) * 10
for symbol in reversed(symbols[1:]):
if abs(n) >= prefix[symbol]:
value = float(n) / prefix[symbol]
return format % locals()
return format % dict(symbol=symbols[0], value=n)
def get_procfs_path():
"""Return updated psutil.PROCFS_PATH constant."""
return sys.modules['psutil'].PROCFS_PATH
if PY3:
def decode(s):
return s.decode(encoding=ENCODING, errors=ENCODING_ERRS)
else:
def decode(s):
return s
# =====================================================================
# --- shell utils
# =====================================================================
@memoize
def term_supports_colors(file=sys.stdout): # pragma: no cover
if os.name == 'nt':
return True
try:
import curses
assert file.isatty()
curses.setupterm()
assert curses.tigetnum("colors") > 0
except Exception:
return False
else:
return True
def hilite(s, color=None, bold=False): # pragma: no cover
"""Return an highlighted version of 'string'."""
if not term_supports_colors():
return s
attr = []
colors = dict(green='32', red='91', brown='33', yellow='93', blue='34',
violet='35', lightblue='36', grey='37', darkgrey='30')
colors[None] = '29'
try:
color = colors[color]
except KeyError:
raise ValueError("invalid color %r; choose between %s" % (
list(colors.keys())))
attr.append(color)
if bold:
attr.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
def print_color(
s, color=None, bold=False, file=sys.stdout): # pragma: no cover
"""Print a colorized version of string."""
if not term_supports_colors():
print(s, file=file) # NOQA
elif POSIX:
print(hilite(s, color, bold), file=file) # NOQA
else:
import ctypes
DEFAULT_COLOR = 7
GetStdHandle = ctypes.windll.Kernel32.GetStdHandle
SetConsoleTextAttribute = \
ctypes.windll.Kernel32.SetConsoleTextAttribute
colors = dict(green=2, red=4, brown=6, yellow=6)
colors[None] = DEFAULT_COLOR
try:
color = colors[color]
except KeyError:
raise ValueError("invalid color %r; choose between %r" % (
color, list(colors.keys())))
if bold and color <= 7:
color += 8
handle_id = -12 if file is sys.stderr else -11
GetStdHandle.restype = ctypes.c_ulong
handle = GetStdHandle(handle_id)
SetConsoleTextAttribute(handle, color)
try:
print(s, file=file) # NOQA
finally:
SetConsoleTextAttribute(handle, DEFAULT_COLOR)
def debug(msg):
"""If PSUTIL_DEBUG env var is set, print a debug message to stderr."""
if PSUTIL_DEBUG:
import inspect
fname, lineno, _, lines, index = inspect.getframeinfo(
inspect.currentframe().f_back)
if isinstance(msg, Exception):
if isinstance(msg, (OSError, IOError, EnvironmentError)):
# ...because str(exc) may contain info about the file name
msg = "ignoring %s" % msg
else:
msg = "ignoring %r" % msg
print("psutil-debug [%s:%s]> %s" % (fname, lineno, msg), # NOQA
file=sys.stderr)
| 29,186 | 30.149413 | 81 | py |
psutil | psutil-master/psutil/_compat.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module which provides compatibility with older Python versions.
This is more future-compatible rather than the opposite (prefer latest
Python 3 way of doing things).
"""
import collections
import contextlib
import errno
import functools
import os
import sys
import types
__all__ = [
# constants
"PY3",
# builtins
"long", "range", "super", "unicode", "basestring",
# literals
"u", "b",
# collections module
"lru_cache",
# shutil module
"which", "get_terminal_size",
# contextlib module
"redirect_stderr",
# python 3 exceptions
"FileNotFoundError", "PermissionError", "ProcessLookupError",
"InterruptedError", "ChildProcessError", "FileExistsError"]
PY3 = sys.version_info[0] == 3
_SENTINEL = object()
if PY3:
long = int
xrange = range
unicode = str
basestring = str
range = range
def u(s):
return s
def b(s):
return s.encode("latin-1")
else:
long = long
range = xrange
unicode = unicode
basestring = basestring
def u(s):
return unicode(s, "unicode_escape")
def b(s):
return s
# --- builtins
# Python 3 super().
# Taken from "future" package.
# Credit: Ryan Kelly
if PY3:
super = super
else:
_builtin_super = super
def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
"""Like Python 3 builtin super(). If called without any arguments
it attempts to infer them at runtime.
"""
if type_ is _SENTINEL:
f = sys._getframe(framedepth)
try:
# Get the function's first positional argument.
type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
except (IndexError, KeyError):
raise RuntimeError('super() used in a function with no args')
try:
# Get the MRO so we can crawl it.
mro = type_or_obj.__mro__
except (AttributeError, RuntimeError):
try:
mro = type_or_obj.__class__.__mro__
except AttributeError:
raise RuntimeError('super() used in a non-newstyle class')
for type_ in mro:
# Find the class that owns the currently-executing method.
for meth in type_.__dict__.values():
# Drill down through any wrappers to the underlying func.
# This handles e.g. classmethod() and staticmethod().
try:
while not isinstance(meth, types.FunctionType):
if isinstance(meth, property):
# Calling __get__ on the property will invoke
# user code which might throw exceptions or
# have side effects
meth = meth.fget
else:
try:
meth = meth.__func__
except AttributeError:
meth = meth.__get__(type_or_obj, type_)
except (AttributeError, TypeError):
continue
if meth.func_code is f.f_code:
break # found
else:
# Not found. Move onto the next class in MRO.
continue
break # found
else:
raise RuntimeError('super() called outside a method')
# Dispatch to builtin super().
if type_or_obj is not _SENTINEL:
return _builtin_super(type_, type_or_obj)
return _builtin_super(type_)
# --- exceptions
if PY3:
FileNotFoundError = FileNotFoundError # NOQA
PermissionError = PermissionError # NOQA
ProcessLookupError = ProcessLookupError # NOQA
InterruptedError = InterruptedError # NOQA
ChildProcessError = ChildProcessError # NOQA
FileExistsError = FileExistsError # NOQA
else:
# https://github.com/PythonCharmers/python-future/blob/exceptions/
# src/future/types/exceptions/pep3151.py
import platform
def _instance_checking_exception(base_exception=Exception):
def wrapped(instance_checker):
class TemporaryClass(base_exception):
def __init__(self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], TemporaryClass):
unwrap_me = args[0]
for attr in dir(unwrap_me):
if not attr.startswith('__'):
setattr(self, attr, getattr(unwrap_me, attr))
else:
super(TemporaryClass, self).__init__(*args, **kwargs)
class __metaclass__(type):
def __instancecheck__(cls, inst):
return instance_checker(inst)
def __subclasscheck__(cls, classinfo):
value = sys.exc_info()[1]
return isinstance(value, cls)
TemporaryClass.__name__ = instance_checker.__name__
TemporaryClass.__doc__ = instance_checker.__doc__
return TemporaryClass
return wrapped
@_instance_checking_exception(EnvironmentError)
def FileNotFoundError(inst):
return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT
@_instance_checking_exception(EnvironmentError)
def ProcessLookupError(inst):
return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH
@_instance_checking_exception(EnvironmentError)
def PermissionError(inst):
return getattr(inst, 'errno', _SENTINEL) in (
errno.EACCES, errno.EPERM)
@_instance_checking_exception(EnvironmentError)
def InterruptedError(inst):
return getattr(inst, 'errno', _SENTINEL) == errno.EINTR
@_instance_checking_exception(EnvironmentError)
def ChildProcessError(inst):
return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD
@_instance_checking_exception(EnvironmentError)
def FileExistsError(inst):
return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST
if platform.python_implementation() != "CPython":
try:
raise OSError(errno.EEXIST, "perm")
except FileExistsError:
pass
except OSError:
raise RuntimeError(
"broken or incompatible Python implementation, see: "
"https://github.com/giampaolo/psutil/issues/1659")
# --- stdlib additions
# py 3.2 functools.lru_cache
# Taken from: http://code.activestate.com/recipes/578078
# Credit: Raymond Hettinger
try:
from functools import lru_cache
except ImportError:
try:
from threading import RLock
except ImportError:
from dummy_threading import RLock
_CacheInfo = collections.namedtuple(
"CacheInfo", ["hits", "misses", "maxsize", "currsize"])
class _HashedSeq(list):
__slots__ = 'hashvalue'
def __init__(self, tup, hash=hash):
self[:] = tup
self.hashvalue = hash(tup)
def __hash__(self):
return self.hashvalue
def _make_key(args, kwds, typed,
kwd_mark=(_SENTINEL, ),
fasttypes=set((int, str, frozenset, type(None))), # noqa
sorted=sorted, tuple=tuple, type=type, len=len):
key = args
if kwds:
sorted_items = sorted(kwds.items())
key += kwd_mark
for item in sorted_items:
key += item
if typed:
key += tuple(type(v) for v in args)
if kwds:
key += tuple(type(v) for k, v in sorted_items)
elif len(key) == 1 and type(key[0]) in fasttypes:
return key[0]
return _HashedSeq(key)
def lru_cache(maxsize=100, typed=False):
"""Least-recently-used cache decorator, see:
http://docs.python.org/3/library/functools.html#functools.lru_cache
"""
def decorating_function(user_function):
cache = {}
stats = [0, 0]
HITS, MISSES = 0, 1
make_key = _make_key
cache_get = cache.get
_len = len
lock = RLock()
root = []
root[:] = [root, root, None, None]
nonlocal_root = [root]
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3
if maxsize == 0:
def wrapper(*args, **kwds):
result = user_function(*args, **kwds)
stats[MISSES] += 1
return result
elif maxsize is None:
def wrapper(*args, **kwds):
key = make_key(args, kwds, typed)
result = cache_get(key, root)
if result is not root:
stats[HITS] += 1
return result
result = user_function(*args, **kwds)
cache[key] = result
stats[MISSES] += 1
return result
else:
def wrapper(*args, **kwds):
if kwds or typed:
key = make_key(args, kwds, typed)
else:
key = args
lock.acquire()
try:
link = cache_get(key)
if link is not None:
root, = nonlocal_root
link_prev, link_next, key, result = link
link_prev[NEXT] = link_next
link_next[PREV] = link_prev
last = root[PREV]
last[NEXT] = root[PREV] = link
link[PREV] = last
link[NEXT] = root
stats[HITS] += 1
return result
finally:
lock.release()
result = user_function(*args, **kwds)
lock.acquire()
try:
root, = nonlocal_root
if key in cache:
pass
elif _len(cache) >= maxsize:
oldroot = root
oldroot[KEY] = key
oldroot[RESULT] = result
root = nonlocal_root[0] = oldroot[NEXT]
oldkey = root[KEY]
root[KEY] = root[RESULT] = None
del cache[oldkey]
cache[key] = oldroot
else:
last = root[PREV]
link = [last, root, key, result]
last[NEXT] = root[PREV] = cache[key] = link
stats[MISSES] += 1
finally:
lock.release()
return result
def cache_info():
"""Report cache statistics"""
lock.acquire()
try:
return _CacheInfo(stats[HITS], stats[MISSES], maxsize,
len(cache))
finally:
lock.release()
def cache_clear():
"""Clear the cache and cache statistics"""
lock.acquire()
try:
cache.clear()
root = nonlocal_root[0]
root[:] = [root, root, None, None]
stats[:] = [0, 0]
finally:
lock.release()
wrapper.__wrapped__ = user_function
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return functools.update_wrapper(wrapper, user_function)
return decorating_function
# python 3.3
try:
from shutil import which
except ImportError:
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode) and
not os.path.isdir(fn))
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if sys.platform == "win32":
if os.curdir not in path:
path.insert(0, os.curdir)
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if normdir not in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
# python 3.3
try:
from shutil import get_terminal_size
except ImportError:
def get_terminal_size(fallback=(80, 24)):
try:
import fcntl
import struct
import termios
except ImportError:
return fallback
else:
try:
# This should work on Linux.
res = struct.unpack(
'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234'))
return (res[1], res[0])
except Exception:
return fallback
# python 3.3
try:
from subprocess import TimeoutExpired as SubprocessTimeoutExpired
except ImportError:
class SubprocessTimeoutExpired(Exception):
pass
# python 3.5
try:
from contextlib import redirect_stderr
except ImportError:
@contextlib.contextmanager
def redirect_stderr(new_target):
original = sys.stderr
try:
sys.stderr = new_target
yield new_target
finally:
sys.stderr = original
| 15,025 | 32.317073 | 78 | py |
psutil | psutil-master/psutil/_psaix.py | # Copyright (c) 2009, Giampaolo Rodola'
# Copyright (c) 2017, Arnon Yaari
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""AIX platform implementation."""
import functools
import glob
import os
import re
import subprocess
import sys
from collections import namedtuple
from . import _common
from . import _psposix
from . import _psutil_aix as cext
from . import _psutil_posix as cext_posix
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import AccessDenied
from ._common import NoSuchProcess
from ._common import ZombieProcess
from ._common import conn_to_ntuple
from ._common import get_procfs_path
from ._common import memoize_when_activated
from ._common import usage_percent
from ._compat import PY3
from ._compat import FileNotFoundError
from ._compat import PermissionError
from ._compat import ProcessLookupError
__extra__all__ = ["PROCFS_PATH"]
# =====================================================================
# --- globals
# =====================================================================
HAS_THREADS = hasattr(cext, "proc_threads")
HAS_NET_IO_COUNTERS = hasattr(cext, "net_io_counters")
HAS_PROC_IO_COUNTERS = hasattr(cext, "proc_io_counters")
PAGE_SIZE = cext_posix.getpagesize()
AF_LINK = cext_posix.AF_LINK
PROC_STATUSES = {
cext.SIDL: _common.STATUS_IDLE,
cext.SZOMB: _common.STATUS_ZOMBIE,
cext.SACTIVE: _common.STATUS_RUNNING,
cext.SSWAP: _common.STATUS_RUNNING, # TODO what status is this?
cext.SSTOP: _common.STATUS_STOPPED,
}
TCP_STATUSES = {
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
cext.TCPS_CLOSED: _common.CONN_CLOSE,
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
cext.TCPS_LISTEN: _common.CONN_LISTEN,
cext.TCPS_CLOSING: _common.CONN_CLOSING,
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}
proc_info_map = dict(
ppid=0,
rss=1,
vms=2,
create_time=3,
nice=4,
num_threads=5,
status=6,
ttynr=7)
# =====================================================================
# --- named tuples
# =====================================================================
# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms'])
# psutil.Process.memory_full_info()
pfullmem = pmem
# psutil.Process.cpu_times()
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
# psutil.virtual_memory()
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
# =====================================================================
# --- memory
# =====================================================================
def virtual_memory():
total, avail, free, pinned, inuse = cext.virtual_mem()
percent = usage_percent((total - avail), total, round_=1)
return svmem(total, avail, percent, inuse, free)
def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
total, free, sin, sout = cext.swap_mem()
used = total - free
percent = usage_percent(used, total, round_=1)
return _common.sswap(total, used, free, percent, sin, sout)
# =====================================================================
# --- CPU
# =====================================================================
def cpu_times():
"""Return system-wide CPU times as a named tuple"""
ret = cext.per_cpu_times()
return scputimes(*[sum(x) for x in zip(*ret)])
def per_cpu_times():
"""Return system per-CPU times as a list of named tuples"""
ret = cext.per_cpu_times()
return [scputimes(*x) for x in ret]
def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
# mimic os.cpu_count() behavior
return None
def cpu_count_cores():
cmd = "lsdev -Cc processor"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if PY3:
stdout, stderr = [x.decode(sys.stdout.encoding)
for x in (stdout, stderr)]
if p.returncode != 0:
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
processors = stdout.strip().splitlines()
return len(processors) or None
def cpu_stats():
"""Return various CPU stats as a named tuple."""
ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats()
return _common.scpustats(
ctx_switches, interrupts, soft_interrupts, syscalls)
# =====================================================================
# --- disks
# =====================================================================
disk_io_counters = cext.disk_io_counters
disk_usage = _psposix.disk_usage
def disk_partitions(all=False):
"""Return system disk partitions."""
# TODO - the filtering logic should be better checked so that
# it tries to reflect 'df' as much as possible
retlist = []
partitions = cext.disk_partitions()
for partition in partitions:
device, mountpoint, fstype, opts = partition
if device == 'none':
device = ''
if not all:
# Differently from, say, Linux, we don't have a list of
# common fs types so the best we can do, AFAIK, is to
# filter by filesystem having a total size > 0.
if not disk_usage(mountpoint).total:
continue
maxfile = maxpath = None # set later
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts,
maxfile, maxpath)
retlist.append(ntuple)
return retlist
# =====================================================================
# --- network
# =====================================================================
net_if_addrs = cext_posix.net_if_addrs
if HAS_NET_IO_COUNTERS:
net_io_counters = cext.net_io_counters
def net_connections(kind, _pid=-1):
"""Return socket connections. If pid == -1 return system-wide
connections (as opposed to connections opened by one process only).
"""
cmap = _common.conn_tmap
if kind not in cmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in cmap])))
families, types = _common.conn_tmap[kind]
rawlist = cext.net_connections(_pid)
ret = []
for item in rawlist:
fd, fam, type_, laddr, raddr, status, pid = item
if fam not in families:
continue
if type_ not in types:
continue
nt = conn_to_ntuple(fd, fam, type_, laddr, raddr, status,
TCP_STATUSES, pid=pid if _pid == -1 else None)
ret.append(nt)
return ret
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
duplex_map = {"Full": NIC_DUPLEX_FULL,
"Half": NIC_DUPLEX_HALF}
names = set([x[0] for x in net_if_addrs()])
ret = {}
for name in names:
mtu = cext_posix.net_if_mtu(name)
flags = cext_posix.net_if_flags(name)
# try to get speed and duplex
# TODO: rewrite this in C (entstat forks, so use truss -f to follow.
# looks like it is using an undocumented ioctl?)
duplex = ""
speed = 0
p = subprocess.Popen(["/usr/bin/entstat", "-d", name],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if PY3:
stdout, stderr = [x.decode(sys.stdout.encoding)
for x in (stdout, stderr)]
if p.returncode == 0:
re_result = re.search(
r"Running: (\d+) Mbps.*?(\w+) Duplex", stdout)
if re_result is not None:
speed = int(re_result.group(1))
duplex = re_result.group(2)
output_flags = ','.join(flags)
isup = 'running' in flags
duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN)
ret[name] = _common.snicstats(isup, duplex, speed, mtu, output_flags)
return ret
# =====================================================================
# --- other system functions
# =====================================================================
def boot_time():
"""The system boot time expressed in seconds since the epoch."""
return cext.boot_time()
def users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = cext.users()
localhost = (':0.0', ':0')
for item in rawlist:
user, tty, hostname, tstamp, user_process, pid = item
# note: the underlying C function includes entries about
# system boot, run level and others. We might want
# to use them in the future.
if not user_process:
continue
if hostname in localhost:
hostname = 'localhost'
nt = _common.suser(user, tty, hostname, tstamp, pid)
retlist.append(nt)
return retlist
# =====================================================================
# --- processes
# =====================================================================
def pids():
"""Returns a list of PIDs currently running on the system."""
return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
def pid_exists(pid):
"""Check for the existence of a unix pid."""
return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo"))
def wrap_exceptions(fun):
"""Call callable into a try/except clause and translate ENOENT,
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except (FileNotFoundError, ProcessLookupError):
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
except PermissionError:
raise AccessDenied(self.pid, self._name)
return wrapper
class Process(object):
"""Wrapper class around underlying C implementation."""
__slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
def __init__(self, pid):
self.pid = pid
self._name = None
self._ppid = None
self._procfs_path = get_procfs_path()
def oneshot_enter(self):
self._proc_basic_info.cache_activate(self)
self._proc_cred.cache_activate(self)
def oneshot_exit(self):
self._proc_basic_info.cache_deactivate(self)
self._proc_cred.cache_deactivate(self)
@wrap_exceptions
@memoize_when_activated
def _proc_basic_info(self):
return cext.proc_basic_info(self.pid, self._procfs_path)
@wrap_exceptions
@memoize_when_activated
def _proc_cred(self):
return cext.proc_cred(self.pid, self._procfs_path)
@wrap_exceptions
def name(self):
if self.pid == 0:
return "swapper"
# note: max 16 characters
return cext.proc_name(self.pid, self._procfs_path).rstrip("\x00")
@wrap_exceptions
def exe(self):
# there is no way to get executable path in AIX other than to guess,
# and guessing is more complex than what's in the wrapping class
cmdline = self.cmdline()
if not cmdline:
return ''
exe = cmdline[0]
if os.path.sep in exe:
# relative or absolute path
if not os.path.isabs(exe):
# if cwd has changed, we're out of luck - this may be wrong!
exe = os.path.abspath(os.path.join(self.cwd(), exe))
if (os.path.isabs(exe) and
os.path.isfile(exe) and
os.access(exe, os.X_OK)):
return exe
# not found, move to search in PATH using basename only
exe = os.path.basename(exe)
# search for exe name PATH
for path in os.environ["PATH"].split(":"):
possible_exe = os.path.abspath(os.path.join(path, exe))
if (os.path.isfile(possible_exe) and
os.access(possible_exe, os.X_OK)):
return possible_exe
return ''
@wrap_exceptions
def cmdline(self):
return cext.proc_args(self.pid)
@wrap_exceptions
def environ(self):
return cext.proc_environ(self.pid)
@wrap_exceptions
def create_time(self):
return self._proc_basic_info()[proc_info_map['create_time']]
@wrap_exceptions
def num_threads(self):
return self._proc_basic_info()[proc_info_map['num_threads']]
if HAS_THREADS:
@wrap_exceptions
def threads(self):
rawlist = cext.proc_threads(self.pid)
retlist = []
for thread_id, utime, stime in rawlist:
ntuple = _common.pthread(thread_id, utime, stime)
retlist.append(ntuple)
# The underlying C implementation retrieves all OS threads
# and filters them by PID. At this point we can't tell whether
# an empty list means there were no connections for process or
# process is no longer active so we force NSP in case the PID
# is no longer there.
if not retlist:
# will raise NSP if process is gone
os.stat('%s/%s' % (self._procfs_path, self.pid))
return retlist
@wrap_exceptions
def connections(self, kind='inet'):
ret = net_connections(kind, _pid=self.pid)
# The underlying C implementation retrieves all OS connections
# and filters them by PID. At this point we can't tell whether
# an empty list means there were no connections for process or
# process is no longer active so we force NSP in case the PID
# is no longer there.
if not ret:
# will raise NSP if process is gone
os.stat('%s/%s' % (self._procfs_path, self.pid))
return ret
@wrap_exceptions
def nice_get(self):
return cext_posix.getpriority(self.pid)
@wrap_exceptions
def nice_set(self, value):
return cext_posix.setpriority(self.pid, value)
@wrap_exceptions
def ppid(self):
self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
return self._ppid
@wrap_exceptions
def uids(self):
real, effective, saved, _, _, _ = self._proc_cred()
return _common.puids(real, effective, saved)
@wrap_exceptions
def gids(self):
_, _, _, real, effective, saved = self._proc_cred()
return _common.puids(real, effective, saved)
@wrap_exceptions
def cpu_times(self):
t = cext.proc_cpu_times(self.pid, self._procfs_path)
return _common.pcputimes(*t)
@wrap_exceptions
def terminal(self):
ttydev = self._proc_basic_info()[proc_info_map['ttynr']]
# convert from 64-bit dev_t to 32-bit dev_t and then map the device
ttydev = (((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF))
# try to match rdev of /dev/pts/* files ttydev
for dev in glob.glob("/dev/**/*"):
if os.stat(dev).st_rdev == ttydev:
return dev
return None
@wrap_exceptions
def cwd(self):
procfs_path = self._procfs_path
try:
result = os.readlink("%s/%s/cwd" % (procfs_path, self.pid))
return result.rstrip('/')
except FileNotFoundError:
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
return ""
@wrap_exceptions
def memory_info(self):
ret = self._proc_basic_info()
rss = ret[proc_info_map['rss']] * 1024
vms = ret[proc_info_map['vms']] * 1024
return pmem(rss, vms)
memory_full_info = memory_info
@wrap_exceptions
def status(self):
code = self._proc_basic_info()[proc_info_map['status']]
# XXX is '?' legit? (we're not supposed to return it anyway)
return PROC_STATUSES.get(code, '?')
def open_files(self):
# TODO rewrite without using procfiles (stat /proc/pid/fd/* and then
# find matching name of the inode)
p = subprocess.Popen(["/usr/bin/procfiles", "-n", str(self.pid)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if PY3:
stdout, stderr = [x.decode(sys.stdout.encoding)
for x in (stdout, stderr)]
if "no such process" in stderr.lower():
raise NoSuchProcess(self.pid, self._name)
procfiles = re.findall(r"(\d+): S_IFREG.*\s*.*name:(.*)\n", stdout)
retlist = []
for fd, path in procfiles:
path = path.strip()
if path.startswith("//"):
path = path[1:]
if path.lower() == "cannot be retrieved":
continue
retlist.append(_common.popenfile(path, int(fd)))
return retlist
@wrap_exceptions
def num_fds(self):
if self.pid == 0: # no /proc/0/fd
return 0
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
@wrap_exceptions
def num_ctx_switches(self):
return _common.pctxsw(
*cext.proc_num_ctx_switches(self.pid))
@wrap_exceptions
def wait(self, timeout=None):
return _psposix.wait_pid(self.pid, timeout, self._name)
if HAS_PROC_IO_COUNTERS:
@wrap_exceptions
def io_counters(self):
try:
rc, wc, rb, wb = cext.proc_io_counters(self.pid)
except OSError:
# if process is terminated, proc_io_counters returns OSError
# instead of NSP
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
raise
return _common.pio(rc, wc, rb, wb)
| 18,665 | 32.571942 | 78 | py |
psutil | psutil-master/psutil/_psbsd.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""FreeBSD, OpenBSD and NetBSD platforms implementation."""
import contextlib
import errno
import functools
import os
import xml.etree.ElementTree as ET
from collections import defaultdict
from collections import namedtuple
from . import _common
from . import _psposix
from . import _psutil_bsd as cext
from . import _psutil_posix as cext_posix
from ._common import FREEBSD
from ._common import NETBSD
from ._common import OPENBSD
from ._common import AccessDenied
from ._common import NoSuchProcess
from ._common import ZombieProcess
from ._common import conn_tmap
from ._common import conn_to_ntuple
from ._common import debug
from ._common import memoize
from ._common import memoize_when_activated
from ._common import usage_percent
from ._compat import FileNotFoundError
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import which
__extra__all__ = []
# =====================================================================
# --- globals
# =====================================================================
if FREEBSD:
PROC_STATUSES = {
cext.SIDL: _common.STATUS_IDLE,
cext.SRUN: _common.STATUS_RUNNING,
cext.SSLEEP: _common.STATUS_SLEEPING,
cext.SSTOP: _common.STATUS_STOPPED,
cext.SZOMB: _common.STATUS_ZOMBIE,
cext.SWAIT: _common.STATUS_WAITING,
cext.SLOCK: _common.STATUS_LOCKED,
}
elif OPENBSD:
PROC_STATUSES = {
cext.SIDL: _common.STATUS_IDLE,
cext.SSLEEP: _common.STATUS_SLEEPING,
cext.SSTOP: _common.STATUS_STOPPED,
# According to /usr/include/sys/proc.h SZOMB is unused.
# test_zombie_process() shows that SDEAD is the right
# equivalent. Also it appears there's no equivalent of
# psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE.
# cext.SZOMB: _common.STATUS_ZOMBIE,
cext.SDEAD: _common.STATUS_ZOMBIE,
cext.SZOMB: _common.STATUS_ZOMBIE,
# From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt
# OpenBSD has SRUN and SONPROC: SRUN indicates that a process
# is runnable but *not* yet running, i.e. is on a run queue.
# SONPROC indicates that the process is actually executing on
# a CPU, i.e. it is no longer on a run queue.
# As such we'll map SRUN to STATUS_WAKING and SONPROC to
# STATUS_RUNNING
cext.SRUN: _common.STATUS_WAKING,
cext.SONPROC: _common.STATUS_RUNNING,
}
elif NETBSD:
PROC_STATUSES = {
cext.SIDL: _common.STATUS_IDLE,
cext.SSLEEP: _common.STATUS_SLEEPING,
cext.SSTOP: _common.STATUS_STOPPED,
cext.SZOMB: _common.STATUS_ZOMBIE,
cext.SRUN: _common.STATUS_WAKING,
cext.SONPROC: _common.STATUS_RUNNING,
}
TCP_STATUSES = {
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
cext.TCPS_CLOSED: _common.CONN_CLOSE,
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
cext.TCPS_LISTEN: _common.CONN_LISTEN,
cext.TCPS_CLOSING: _common.CONN_CLOSING,
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}
PAGESIZE = cext_posix.getpagesize()
AF_LINK = cext_posix.AF_LINK
HAS_PER_CPU_TIMES = hasattr(cext, "per_cpu_times")
HAS_PROC_NUM_THREADS = hasattr(cext, "proc_num_threads")
HAS_PROC_OPEN_FILES = hasattr(cext, 'proc_open_files')
HAS_PROC_NUM_FDS = hasattr(cext, 'proc_num_fds')
kinfo_proc_map = dict(
ppid=0,
status=1,
real_uid=2,
effective_uid=3,
saved_uid=4,
real_gid=5,
effective_gid=6,
saved_gid=7,
ttynr=8,
create_time=9,
ctx_switches_vol=10,
ctx_switches_unvol=11,
read_io_count=12,
write_io_count=13,
user_time=14,
sys_time=15,
ch_user_time=16,
ch_sys_time=17,
rss=18,
vms=19,
memtext=20,
memdata=21,
memstack=22,
cpunum=23,
name=24,
)
# =====================================================================
# --- named tuples
# =====================================================================
# psutil.virtual_memory()
svmem = namedtuple(
'svmem', ['total', 'available', 'percent', 'used', 'free',
'active', 'inactive', 'buffers', 'cached', 'shared', 'wired'])
# psutil.cpu_times()
scputimes = namedtuple(
'scputimes', ['user', 'nice', 'system', 'idle', 'irq'])
# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms', 'text', 'data', 'stack'])
# psutil.Process.memory_full_info()
pfullmem = pmem
# psutil.Process.cpu_times()
pcputimes = namedtuple('pcputimes',
['user', 'system', 'children_user', 'children_system'])
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple(
'pmmap_grouped', 'path rss, private, ref_count, shadow_count')
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
'pmmap_ext', 'addr, perms path rss, private, ref_count, shadow_count')
# psutil.disk_io_counters()
if FREEBSD:
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
'read_bytes', 'write_bytes',
'read_time', 'write_time',
'busy_time'])
else:
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
'read_bytes', 'write_bytes'])
# =====================================================================
# --- memory
# =====================================================================
def virtual_memory():
mem = cext.virtual_mem()
if NETBSD:
total, free, active, inactive, wired, cached = mem
# On NetBSD buffers and shared mem is determined via /proc.
# The C ext set them to 0.
with open('/proc/meminfo', 'rb') as f:
for line in f:
if line.startswith(b'Buffers:'):
buffers = int(line.split()[1]) * 1024
elif line.startswith(b'MemShared:'):
shared = int(line.split()[1]) * 1024
# Before avail was calculated as (inactive + cached + free),
# same as zabbix, but it turned out it could exceed total (see
# #2233), so zabbix seems to be wrong. Htop calculates it
# differently, and the used value seem more realistic, so let's
# match htop.
# https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162 # noqa
# https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135 # noqa
used = active + wired
avail = total - used
else:
total, free, active, inactive, wired, cached, buffers, shared = mem
# matches freebsd-memory CLI:
# * https://people.freebsd.org/~rse/dist/freebsd-memory
# * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt
# matches zabbix:
# * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143 # noqa
avail = inactive + cached + free
used = active + wired + cached
percent = usage_percent((total - avail), total, round_=1)
return svmem(total, avail, percent, used, free,
active, inactive, buffers, cached, shared, wired)
def swap_memory():
"""System swap memory as (total, used, free, sin, sout) namedtuple."""
total, used, free, sin, sout = cext.swap_mem()
percent = usage_percent(used, total, round_=1)
return _common.sswap(total, used, free, percent, sin, sout)
# =====================================================================
# --- CPU
# =====================================================================
def cpu_times():
"""Return system per-CPU times as a namedtuple"""
user, nice, system, idle, irq = cext.cpu_times()
return scputimes(user, nice, system, idle, irq)
if HAS_PER_CPU_TIMES:
def per_cpu_times():
"""Return system CPU times as a namedtuple"""
ret = []
for cpu_t in cext.per_cpu_times():
user, nice, system, idle, irq = cpu_t
item = scputimes(user, nice, system, idle, irq)
ret.append(item)
return ret
else:
# XXX
# Ok, this is very dirty.
# On FreeBSD < 8 we cannot gather per-cpu information, see:
# https://github.com/giampaolo/psutil/issues/226
# If num cpus > 1, on first call we return single cpu times to avoid a
# crash at psutil import time.
# Next calls will fail with NotImplementedError
def per_cpu_times():
"""Return system CPU times as a namedtuple"""
if cpu_count_logical() == 1:
return [cpu_times()]
if per_cpu_times.__called__:
raise NotImplementedError("supported only starting from FreeBSD 8")
per_cpu_times.__called__ = True
return [cpu_times()]
per_cpu_times.__called__ = False
def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
return cext.cpu_count_logical()
if OPENBSD or NETBSD:
def cpu_count_cores():
# OpenBSD and NetBSD do not implement this.
return 1 if cpu_count_logical() == 1 else None
else:
def cpu_count_cores():
"""Return the number of CPU cores in the system."""
# From the C module we'll get an XML string similar to this:
# http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html
# We may get None in case "sysctl kern.sched.topology_spec"
# is not supported on this BSD version, in which case we'll mimic
# os.cpu_count() and return None.
ret = None
s = cext.cpu_topology()
if s is not None:
# get rid of padding chars appended at the end of the string
index = s.rfind("</groups>")
if index != -1:
s = s[:index + 9]
root = ET.fromstring(s)
try:
ret = len(root.findall('group/children/group/cpu')) or None
finally:
# needed otherwise it will memleak
root.clear()
if not ret:
# If logical CPUs == 1 it's obvious we' have only 1 core.
if cpu_count_logical() == 1:
return 1
return ret
def cpu_stats():
"""Return various CPU stats as a named tuple."""
if FREEBSD:
# Note: the C ext is returning some metrics we are not exposing:
# traps.
ctxsw, intrs, soft_intrs, syscalls, traps = cext.cpu_stats()
elif NETBSD:
# XXX
# Note about intrs: the C extension returns 0. intrs
# can be determined via /proc/stat; it has the same value as
# soft_intrs thought so the kernel is faking it (?).
#
# Note about syscalls: the C extension always sets it to 0 (?).
#
# Note: the C ext is returning some metrics we are not exposing:
# traps, faults and forks.
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \
cext.cpu_stats()
with open('/proc/stat', 'rb') as f:
for line in f:
if line.startswith(b'intr'):
intrs = int(line.split()[1])
elif OPENBSD:
# Note: the C ext is returning some metrics we are not exposing:
# traps, faults and forks.
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \
cext.cpu_stats()
return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls)
if FREEBSD:
def cpu_freq():
"""Return frequency metrics for CPUs. As of Dec 2018 only
CPU 0 appears to be supported by FreeBSD and all other cores
match the frequency of CPU 0.
"""
ret = []
num_cpus = cpu_count_logical()
for cpu in range(num_cpus):
try:
current, available_freq = cext.cpu_freq(cpu)
except NotImplementedError:
continue
if available_freq:
try:
min_freq = int(available_freq.split(" ")[-1].split("/")[0])
except (IndexError, ValueError):
min_freq = None
try:
max_freq = int(available_freq.split(" ")[0].split("/")[0])
except (IndexError, ValueError):
max_freq = None
ret.append(_common.scpufreq(current, min_freq, max_freq))
return ret
elif OPENBSD:
def cpu_freq():
curr = float(cext.cpu_freq())
return [_common.scpufreq(curr, 0.0, 0.0)]
# =====================================================================
# --- disks
# =====================================================================
def disk_partitions(all=False):
"""Return mounted disk partitions as a list of namedtuples.
'all' argument is ignored, see:
https://github.com/giampaolo/psutil/issues/906
"""
retlist = []
partitions = cext.disk_partitions()
for partition in partitions:
device, mountpoint, fstype, opts = partition
maxfile = maxpath = None # set later
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts,
maxfile, maxpath)
retlist.append(ntuple)
return retlist
disk_usage = _psposix.disk_usage
disk_io_counters = cext.disk_io_counters
# =====================================================================
# --- network
# =====================================================================
net_io_counters = cext.net_io_counters
net_if_addrs = cext_posix.net_if_addrs
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
names = net_io_counters().keys()
ret = {}
for name in names:
try:
mtu = cext_posix.net_if_mtu(name)
flags = cext_posix.net_if_flags(name)
duplex, speed = cext_posix.net_if_duplex_speed(name)
except OSError as err:
# https://github.com/giampaolo/psutil/issues/1279
if err.errno != errno.ENODEV:
raise
else:
if hasattr(_common, 'NicDuplex'):
duplex = _common.NicDuplex(duplex)
output_flags = ','.join(flags)
isup = 'running' in flags
ret[name] = _common.snicstats(isup, duplex, speed, mtu,
output_flags)
return ret
def net_connections(kind):
"""System-wide network connections."""
if kind not in _common.conn_tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in conn_tmap])))
families, types = conn_tmap[kind]
ret = set()
if OPENBSD:
rawlist = cext.net_connections(-1, families, types)
elif NETBSD:
rawlist = cext.net_connections(-1)
else: # FreeBSD
rawlist = cext.net_connections()
for item in rawlist:
fd, fam, type, laddr, raddr, status, pid = item
if NETBSD or FREEBSD:
# OpenBSD implements filtering in C
if (fam not in families) or (type not in types):
continue
nt = conn_to_ntuple(fd, fam, type, laddr, raddr,
status, TCP_STATUSES, pid)
ret.add(nt)
return list(ret)
# =====================================================================
# --- sensors
# =====================================================================
if FREEBSD:
def sensors_battery():
"""Return battery info."""
try:
percent, minsleft, power_plugged = cext.sensors_battery()
except NotImplementedError:
# See: https://github.com/giampaolo/psutil/issues/1074
return None
power_plugged = power_plugged == 1
if power_plugged:
secsleft = _common.POWER_TIME_UNLIMITED
elif minsleft == -1:
secsleft = _common.POWER_TIME_UNKNOWN
else:
secsleft = minsleft * 60
return _common.sbattery(percent, secsleft, power_plugged)
def sensors_temperatures():
"""Return CPU cores temperatures if available, else an empty dict."""
ret = defaultdict(list)
num_cpus = cpu_count_logical()
for cpu in range(num_cpus):
try:
current, high = cext.sensors_cpu_temperature(cpu)
if high <= 0:
high = None
name = "Core %s" % cpu
ret["coretemp"].append(
_common.shwtemp(name, current, high, high))
except NotImplementedError:
pass
return ret
# =====================================================================
# --- other system functions
# =====================================================================
def boot_time():
"""The system boot time expressed in seconds since the epoch."""
return cext.boot_time()
def users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = cext.users()
for item in rawlist:
user, tty, hostname, tstamp, pid = item
if pid == -1:
assert OPENBSD
pid = None
if tty == '~':
continue # reboot or shutdown
nt = _common.suser(user, tty or None, hostname, tstamp, pid)
retlist.append(nt)
return retlist
# =====================================================================
# --- processes
# =====================================================================
@memoize
def _pid_0_exists():
try:
Process(0).name()
except NoSuchProcess:
return False
except AccessDenied:
return True
else:
return True
def pids():
"""Returns a list of PIDs currently running on the system."""
ret = cext.pids()
if OPENBSD and (0 not in ret) and _pid_0_exists():
# On OpenBSD the kernel does not return PID 0 (neither does
# ps) but it's actually querable (Process(0) will succeed).
ret.insert(0, 0)
return ret
if OPENBSD or NETBSD:
def pid_exists(pid):
"""Return True if pid exists."""
exists = _psposix.pid_exists(pid)
if not exists:
# We do this because _psposix.pid_exists() lies in case of
# zombie processes.
return pid in pids()
else:
return True
else:
pid_exists = _psposix.pid_exists
def is_zombie(pid):
try:
st = cext.proc_oneshot_info(pid)[kinfo_proc_map['status']]
return PROC_STATUSES.get(st) == _common.STATUS_ZOMBIE
except Exception:
return False
def wrap_exceptions(fun):
"""Decorator which translates bare OSError exceptions into
NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except ProcessLookupError:
if is_zombie(self.pid):
raise ZombieProcess(self.pid, self._name, self._ppid)
else:
raise NoSuchProcess(self.pid, self._name)
except PermissionError:
raise AccessDenied(self.pid, self._name)
except OSError:
if self.pid == 0:
if 0 in pids():
raise AccessDenied(self.pid, self._name)
else:
raise
raise
return wrapper
@contextlib.contextmanager
def wrap_exceptions_procfs(inst):
"""Same as above, for routines relying on reading /proc fs."""
try:
yield
except (ProcessLookupError, FileNotFoundError):
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if is_zombie(inst.pid):
raise ZombieProcess(inst.pid, inst._name, inst._ppid)
else:
raise NoSuchProcess(inst.pid, inst._name)
except PermissionError:
raise AccessDenied(inst.pid, inst._name)
class Process(object):
"""Wrapper class around underlying C implementation."""
__slots__ = ["pid", "_name", "_ppid", "_cache"]
def __init__(self, pid):
self.pid = pid
self._name = None
self._ppid = None
def _assert_alive(self):
"""Raise NSP if the process disappeared on us."""
# For those C function who do not raise NSP, possibly returning
# incorrect or incomplete result.
cext.proc_name(self.pid)
@wrap_exceptions
@memoize_when_activated
def oneshot(self):
"""Retrieves multiple process info in one shot as a raw tuple."""
ret = cext.proc_oneshot_info(self.pid)
assert len(ret) == len(kinfo_proc_map)
return ret
def oneshot_enter(self):
self.oneshot.cache_activate(self)
def oneshot_exit(self):
self.oneshot.cache_deactivate(self)
@wrap_exceptions
def name(self):
name = self.oneshot()[kinfo_proc_map['name']]
return name if name is not None else cext.proc_name(self.pid)
@wrap_exceptions
def exe(self):
if FREEBSD:
if self.pid == 0:
return '' # else NSP
return cext.proc_exe(self.pid)
elif NETBSD:
if self.pid == 0:
# /proc/0 dir exists but /proc/0/exe doesn't
return ""
with wrap_exceptions_procfs(self):
return os.readlink("/proc/%s/exe" % self.pid)
else:
# OpenBSD: exe cannot be determined; references:
# https://chromium.googlesource.com/chromium/src/base/+/
# master/base_paths_posix.cc
# We try our best guess by using which against the first
# cmdline arg (may return None).
cmdline = self.cmdline()
if cmdline:
return which(cmdline[0]) or ""
else:
return ""
@wrap_exceptions
def cmdline(self):
if OPENBSD and self.pid == 0:
return [] # ...else it crashes
elif NETBSD:
# XXX - most of the times the underlying sysctl() call on
# NetBSD and OpenBSD returns a truncated string. Also
# /proc/pid/cmdline behaves the same so it looks like this
# is a kernel bug.
try:
return cext.proc_cmdline(self.pid)
except OSError as err:
if err.errno == errno.EINVAL:
if is_zombie(self.pid):
raise ZombieProcess(self.pid, self._name, self._ppid)
elif not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name, self._ppid)
else:
# XXX: this happens with unicode tests. It means the C
# routine is unable to decode invalid unicode chars.
debug("ignoring %r and returning an empty list" % err)
return []
else:
raise
else:
return cext.proc_cmdline(self.pid)
@wrap_exceptions
def environ(self):
return cext.proc_environ(self.pid)
@wrap_exceptions
def terminal(self):
tty_nr = self.oneshot()[kinfo_proc_map['ttynr']]
tmap = _psposix.get_terminal_map()
try:
return tmap[tty_nr]
except KeyError:
return None
@wrap_exceptions
def ppid(self):
self._ppid = self.oneshot()[kinfo_proc_map['ppid']]
return self._ppid
@wrap_exceptions
def uids(self):
rawtuple = self.oneshot()
return _common.puids(
rawtuple[kinfo_proc_map['real_uid']],
rawtuple[kinfo_proc_map['effective_uid']],
rawtuple[kinfo_proc_map['saved_uid']])
@wrap_exceptions
def gids(self):
rawtuple = self.oneshot()
return _common.pgids(
rawtuple[kinfo_proc_map['real_gid']],
rawtuple[kinfo_proc_map['effective_gid']],
rawtuple[kinfo_proc_map['saved_gid']])
@wrap_exceptions
def cpu_times(self):
rawtuple = self.oneshot()
return _common.pcputimes(
rawtuple[kinfo_proc_map['user_time']],
rawtuple[kinfo_proc_map['sys_time']],
rawtuple[kinfo_proc_map['ch_user_time']],
rawtuple[kinfo_proc_map['ch_sys_time']])
if FREEBSD:
@wrap_exceptions
def cpu_num(self):
return self.oneshot()[kinfo_proc_map['cpunum']]
@wrap_exceptions
def memory_info(self):
rawtuple = self.oneshot()
return pmem(
rawtuple[kinfo_proc_map['rss']],
rawtuple[kinfo_proc_map['vms']],
rawtuple[kinfo_proc_map['memtext']],
rawtuple[kinfo_proc_map['memdata']],
rawtuple[kinfo_proc_map['memstack']])
memory_full_info = memory_info
@wrap_exceptions
def create_time(self):
return self.oneshot()[kinfo_proc_map['create_time']]
@wrap_exceptions
def num_threads(self):
if HAS_PROC_NUM_THREADS:
# FreeBSD
return cext.proc_num_threads(self.pid)
else:
return len(self.threads())
@wrap_exceptions
def num_ctx_switches(self):
rawtuple = self.oneshot()
return _common.pctxsw(
rawtuple[kinfo_proc_map['ctx_switches_vol']],
rawtuple[kinfo_proc_map['ctx_switches_unvol']])
@wrap_exceptions
def threads(self):
# Note: on OpenSBD this (/dev/mem) requires root access.
rawlist = cext.proc_threads(self.pid)
retlist = []
for thread_id, utime, stime in rawlist:
ntuple = _common.pthread(thread_id, utime, stime)
retlist.append(ntuple)
if OPENBSD:
self._assert_alive()
return retlist
@wrap_exceptions
def connections(self, kind='inet'):
if kind not in conn_tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in conn_tmap])))
families, types = conn_tmap[kind]
ret = []
if NETBSD:
rawlist = cext.net_connections(self.pid)
elif OPENBSD:
rawlist = cext.net_connections(self.pid, families, types)
else: # FreeBSD
rawlist = cext.proc_connections(self.pid, families, types)
for item in rawlist:
fd, fam, type, laddr, raddr, status = item[:6]
if NETBSD:
# FreeBSD and OpenBSD implement filtering in C
if (fam not in families) or (type not in types):
continue
nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status,
TCP_STATUSES)
ret.append(nt)
self._assert_alive()
return ret
@wrap_exceptions
def wait(self, timeout=None):
return _psposix.wait_pid(self.pid, timeout, self._name)
@wrap_exceptions
def nice_get(self):
return cext_posix.getpriority(self.pid)
@wrap_exceptions
def nice_set(self, value):
return cext_posix.setpriority(self.pid, value)
@wrap_exceptions
def status(self):
code = self.oneshot()[kinfo_proc_map['status']]
# XXX is '?' legit? (we're not supposed to return it anyway)
return PROC_STATUSES.get(code, '?')
@wrap_exceptions
def io_counters(self):
rawtuple = self.oneshot()
return _common.pio(
rawtuple[kinfo_proc_map['read_io_count']],
rawtuple[kinfo_proc_map['write_io_count']],
-1,
-1)
@wrap_exceptions
def cwd(self):
"""Return process current working directory."""
# sometimes we get an empty string, in which case we turn
# it into None
if OPENBSD and self.pid == 0:
return "" # ...else it would raise EINVAL
elif NETBSD or HAS_PROC_OPEN_FILES:
# FreeBSD < 8 does not support functions based on
# kinfo_getfile() and kinfo_getvmmap()
return cext.proc_cwd(self.pid)
else:
raise NotImplementedError(
"supported only starting from FreeBSD 8" if
FREEBSD else "")
nt_mmap_grouped = namedtuple(
'mmap', 'path rss, private, ref_count, shadow_count')
nt_mmap_ext = namedtuple(
'mmap', 'addr, perms path rss, private, ref_count, shadow_count')
def _not_implemented(self):
raise NotImplementedError
# FreeBSD < 8 does not support functions based on kinfo_getfile()
# and kinfo_getvmmap()
if HAS_PROC_OPEN_FILES:
@wrap_exceptions
def open_files(self):
"""Return files opened by process as a list of namedtuples."""
rawlist = cext.proc_open_files(self.pid)
return [_common.popenfile(path, fd) for path, fd in rawlist]
else:
open_files = _not_implemented
# FreeBSD < 8 does not support functions based on kinfo_getfile()
# and kinfo_getvmmap()
if HAS_PROC_NUM_FDS:
@wrap_exceptions
def num_fds(self):
"""Return the number of file descriptors opened by this process."""
ret = cext.proc_num_fds(self.pid)
if NETBSD:
self._assert_alive()
return ret
else:
num_fds = _not_implemented
# --- FreeBSD only APIs
if FREEBSD:
@wrap_exceptions
def cpu_affinity_get(self):
return cext.proc_cpu_affinity_get(self.pid)
@wrap_exceptions
def cpu_affinity_set(self, cpus):
# Pre-emptively check if CPUs are valid because the C
# function has a weird behavior in case of invalid CPUs,
# see: https://github.com/giampaolo/psutil/issues/586
allcpus = tuple(range(len(per_cpu_times())))
for cpu in cpus:
if cpu not in allcpus:
raise ValueError("invalid CPU #%i (choose between %s)"
% (cpu, allcpus))
try:
cext.proc_cpu_affinity_set(self.pid, cpus)
except OSError as err:
# 'man cpuset_setaffinity' about EDEADLK:
# <<the call would leave a thread without a valid CPU to run
# on because the set does not overlap with the thread's
# anonymous mask>>
if err.errno in (errno.EINVAL, errno.EDEADLK):
for cpu in cpus:
if cpu not in allcpus:
raise ValueError(
"invalid CPU #%i (choose between %s)" % (
cpu, allcpus))
raise
@wrap_exceptions
def memory_maps(self):
return cext.proc_memory_maps(self.pid)
@wrap_exceptions
def rlimit(self, resource, limits=None):
if limits is None:
return cext.proc_getrlimit(self.pid, resource)
else:
if len(limits) != 2:
raise ValueError(
"second argument must be a (soft, hard) tuple, "
"got %s" % repr(limits))
soft, hard = limits
return cext.proc_setrlimit(self.pid, resource, soft, hard)
| 31,877 | 33.277419 | 107 | py |
psutil | psutil-master/psutil/_pslinux.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Linux platform implementation."""
from __future__ import division
import base64
import collections
import errno
import functools
import glob
import os
import re
import socket
import struct
import sys
import traceback
import warnings
from collections import defaultdict
from collections import namedtuple
from . import _common
from . import _psposix
from . import _psutil_linux as cext
from . import _psutil_posix as cext_posix
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import AccessDenied
from ._common import NoSuchProcess
from ._common import ZombieProcess
from ._common import bcat
from ._common import cat
from ._common import debug
from ._common import decode
from ._common import get_procfs_path
from ._common import isfile_strict
from ._common import memoize
from ._common import memoize_when_activated
from ._common import open_binary
from ._common import open_text
from ._common import parse_environ_block
from ._common import path_exists_strict
from ._common import supports_ipv6
from ._common import usage_percent
from ._compat import PY3
from ._compat import FileNotFoundError
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import b
from ._compat import basestring
if sys.version_info >= (3, 4):
import enum
else:
enum = None
__extra__all__ = [
#
'PROCFS_PATH',
# io prio constants
"IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
"IOPRIO_CLASS_IDLE",
# connection status constants
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", ]
# =====================================================================
# --- globals
# =====================================================================
POWER_SUPPLY_PATH = "/sys/class/power_supply"
HAS_PROC_SMAPS = os.path.exists('/proc/%s/smaps' % os.getpid())
HAS_PROC_SMAPS_ROLLUP = os.path.exists('/proc/%s/smaps_rollup' % os.getpid())
HAS_PROC_IO_PRIORITY = hasattr(cext, "proc_ioprio_get")
HAS_CPU_AFFINITY = hasattr(cext, "proc_cpu_affinity_get")
# Number of clock ticks per second
CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
PAGESIZE = cext_posix.getpagesize()
BOOT_TIME = None # set later
LITTLE_ENDIAN = sys.byteorder == 'little'
# "man iostat" states that sectors are equivalent with blocks and have
# a size of 512 bytes. Despite this value can be queried at runtime
# via /sys/block/{DISK}/queue/hw_sector_size and results may vary
# between 1k, 2k, or 4k... 512 appears to be a magic constant used
# throughout Linux source code:
# * https://stackoverflow.com/a/38136179/376587
# * https://lists.gt.net/linux/kernel/2241060
# * https://github.com/giampaolo/psutil/issues/1305
# * https://github.com/torvalds/linux/blob/
# 4f671fe2f9523a1ea206f63fe60a7c7b3a56d5c7/include/linux/bio.h#L99
# * https://lkml.org/lkml/2015/8/17/234
DISK_SECTOR_SIZE = 512
if enum is None:
AF_LINK = socket.AF_PACKET
else:
AddressFamily = enum.IntEnum('AddressFamily',
{'AF_LINK': int(socket.AF_PACKET)})
AF_LINK = AddressFamily.AF_LINK
# ioprio_* constants http://linux.die.net/man/2/ioprio_get
if enum is None:
IOPRIO_CLASS_NONE = 0
IOPRIO_CLASS_RT = 1
IOPRIO_CLASS_BE = 2
IOPRIO_CLASS_IDLE = 3
else:
class IOPriority(enum.IntEnum):
IOPRIO_CLASS_NONE = 0
IOPRIO_CLASS_RT = 1
IOPRIO_CLASS_BE = 2
IOPRIO_CLASS_IDLE = 3
globals().update(IOPriority.__members__)
# See:
# https://github.com/torvalds/linux/blame/master/fs/proc/array.c
# ...and (TASK_* constants):
# https://github.com/torvalds/linux/blob/master/include/linux/sched.h
PROC_STATUSES = {
"R": _common.STATUS_RUNNING,
"S": _common.STATUS_SLEEPING,
"D": _common.STATUS_DISK_SLEEP,
"T": _common.STATUS_STOPPED,
"t": _common.STATUS_TRACING_STOP,
"Z": _common.STATUS_ZOMBIE,
"X": _common.STATUS_DEAD,
"x": _common.STATUS_DEAD,
"K": _common.STATUS_WAKE_KILL,
"W": _common.STATUS_WAKING,
"I": _common.STATUS_IDLE,
"P": _common.STATUS_PARKED,
}
# https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h
TCP_STATUSES = {
"01": _common.CONN_ESTABLISHED,
"02": _common.CONN_SYN_SENT,
"03": _common.CONN_SYN_RECV,
"04": _common.CONN_FIN_WAIT1,
"05": _common.CONN_FIN_WAIT2,
"06": _common.CONN_TIME_WAIT,
"07": _common.CONN_CLOSE,
"08": _common.CONN_CLOSE_WAIT,
"09": _common.CONN_LAST_ACK,
"0A": _common.CONN_LISTEN,
"0B": _common.CONN_CLOSING
}
# =====================================================================
# --- named tuples
# =====================================================================
# psutil.virtual_memory()
svmem = namedtuple(
'svmem', ['total', 'available', 'percent', 'used', 'free',
'active', 'inactive', 'buffers', 'cached', 'shared', 'slab'])
# psutil.disk_io_counters()
sdiskio = namedtuple(
'sdiskio', ['read_count', 'write_count',
'read_bytes', 'write_bytes',
'read_time', 'write_time',
'read_merged_count', 'write_merged_count',
'busy_time'])
# psutil.Process().open_files()
popenfile = namedtuple(
'popenfile', ['path', 'fd', 'position', 'mode', 'flags'])
# psutil.Process().memory_info()
pmem = namedtuple('pmem', 'rss vms shared text lib data dirty')
# psutil.Process().memory_full_info()
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', 'pss', 'swap'))
# psutil.Process().memory_maps(grouped=True)
pmmap_grouped = namedtuple(
'pmmap_grouped',
['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty',
'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap'])
# psutil.Process().memory_maps(grouped=False)
pmmap_ext = namedtuple(
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
# psutil.Process.io_counters()
pio = namedtuple('pio', ['read_count', 'write_count',
'read_bytes', 'write_bytes',
'read_chars', 'write_chars'])
# psutil.Process.cpu_times()
pcputimes = namedtuple('pcputimes',
['user', 'system', 'children_user', 'children_system',
'iowait'])
# =====================================================================
# --- utils
# =====================================================================
def readlink(path):
"""Wrapper around os.readlink()."""
assert isinstance(path, basestring), path
path = os.readlink(path)
# readlink() might return paths containing null bytes ('\x00')
# resulting in "TypeError: must be encoded string without NULL
# bytes, not str" errors when the string is passed to other
# fs-related functions (os.*, open(), ...).
# Apparently everything after '\x00' is garbage (we can have
# ' (deleted)', 'new' and possibly others), see:
# https://github.com/giampaolo/psutil/issues/717
path = path.split('\x00')[0]
# Certain paths have ' (deleted)' appended. Usually this is
# bogus as the file actually exists. Even if it doesn't we
# don't care.
if path.endswith(' (deleted)') and not path_exists_strict(path):
path = path[:-10]
return path
def file_flags_to_mode(flags):
"""Convert file's open() flags into a readable string.
Used by Process.open_files().
"""
modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
if flags & os.O_APPEND:
mode = mode.replace('w', 'a', 1)
mode = mode.replace('w+', 'r+')
# possible values: r, w, a, r+, a+
return mode
def is_storage_device(name):
"""Return True if the given name refers to a root device (e.g.
"sda", "nvme0n1") as opposed to a logical partition (e.g. "sda1",
"nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
return True.
"""
# Re-adapted from iostat source code, see:
# https://github.com/sysstat/sysstat/blob/
# 97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
# Some devices may have a slash in their name (e.g. cciss/c0d0...).
name = name.replace('/', '!')
including_virtual = True
if including_virtual:
path = "/sys/block/%s" % name
else:
path = "/sys/block/%s/device" % name
return os.access(path, os.F_OK)
@memoize
def set_scputimes_ntuple(procfs_path):
"""Set a namedtuple of variable fields depending on the CPU times
available on this Linux kernel version which may be:
(user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
[guest_nice]]])
Used by cpu_times() function.
"""
global scputimes
with open_binary('%s/stat' % procfs_path) as f:
values = f.readline().split()[1:]
fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
vlen = len(values)
if vlen >= 8:
# Linux >= 2.6.11
fields.append('steal')
if vlen >= 9:
# Linux >= 2.6.24
fields.append('guest')
if vlen >= 10:
# Linux >= 3.2.0
fields.append('guest_nice')
scputimes = namedtuple('scputimes', fields)
try:
set_scputimes_ntuple("/proc")
except Exception: # pragma: no cover
# Don't want to crash at import time.
traceback.print_exc()
scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)
# =====================================================================
# --- prlimit
# =====================================================================
# Backport of resource.prlimit() for Python 2. Originally this was done
# in C, but CentOS-6 which we use to create manylinux wheels is too old
# and does not support prlimit() syscall. As such the resulting wheel
# would not include prlimit(), even when installed on newer systems.
# This is the only part of psutil using ctypes.
prlimit = None
try:
from resource import prlimit # python >= 3.4
except ImportError:
import ctypes
libc = ctypes.CDLL(None, use_errno=True)
if hasattr(libc, "prlimit"):
def prlimit(pid, resource_, limits=None):
class StructRlimit(ctypes.Structure):
_fields_ = [('rlim_cur', ctypes.c_longlong),
('rlim_max', ctypes.c_longlong)]
current = StructRlimit()
if limits is None:
# get
ret = libc.prlimit(pid, resource_, None, ctypes.byref(current))
else:
# set
new = StructRlimit()
new.rlim_cur = limits[0]
new.rlim_max = limits[1]
ret = libc.prlimit(
pid, resource_, ctypes.byref(new), ctypes.byref(current))
if ret != 0:
errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_))
return (current.rlim_cur, current.rlim_max)
if prlimit is not None:
__extra__all__.extend(
[x for x in dir(cext) if x.startswith('RLIM') and x.isupper()])
# =====================================================================
# --- system memory
# =====================================================================
def calculate_avail_vmem(mems):
"""Fallback for kernels < 3.14 where /proc/meminfo does not provide
"MemAvailable", see:
https://blog.famzah.net/2014/09/24/
This code reimplements the algorithm outlined here:
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
We use this function also when "MemAvailable" returns 0 (possibly a
kernel bug, see: https://github.com/giampaolo/psutil/issues/1915).
In that case this routine matches "free" CLI tool result ("available"
column).
XXX: on recent kernels this calculation may differ by ~1.5% compared
to "MemAvailable:", as it's calculated slightly differently.
It is still way more realistic than doing (free + cached) though.
See:
* https://gitlab.com/procps-ng/procps/issues/42
* https://github.com/famzah/linux-memavailable-procfs/issues/2
"""
# Note about "fallback" value. According to:
# https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
# commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
# ...long ago "available" memory was calculated as (free + cached),
# We use fallback when one of these is missing from /proc/meminfo:
# "Active(file)": introduced in 2.6.28 / Dec 2008
# "Inactive(file)": introduced in 2.6.28 / Dec 2008
# "SReclaimable": introduced in 2.6.19 / Nov 2006
# /proc/zoneinfo: introduced in 2.6.13 / Aug 2005
free = mems[b'MemFree:']
fallback = free + mems.get(b"Cached:", 0)
try:
lru_active_file = mems[b'Active(file):']
lru_inactive_file = mems[b'Inactive(file):']
slab_reclaimable = mems[b'SReclaimable:']
except KeyError as err:
debug("%r is missing from /proc/meminfo; using an approximation "
"for calculating available memory" % err.args[0])
return fallback
try:
f = open_binary('%s/zoneinfo' % get_procfs_path())
except IOError:
return fallback # kernel 2.6.13
watermark_low = 0
with f:
for line in f:
line = line.strip()
if line.startswith(b'low'):
watermark_low += int(line.split()[1])
watermark_low *= PAGESIZE
avail = free - watermark_low
pagecache = lru_active_file + lru_inactive_file
pagecache -= min(pagecache / 2, watermark_low)
avail += pagecache
avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low)
return int(avail)
def virtual_memory():
"""Report virtual memory stats.
This implementation mimicks procps-ng-3.3.12, aka "free" CLI tool:
https://gitlab.com/procps-ng/procps/blob/
24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L778-791
The returned values are supposed to match both "free" and "vmstat -s"
CLI tools.
"""
missing_fields = []
mems = {}
with open_binary('%s/meminfo' % get_procfs_path()) as f:
for line in f:
fields = line.split()
mems[fields[0]] = int(fields[1]) * 1024
# /proc doc states that the available fields in /proc/meminfo vary
# by architecture and compile options, but these 3 values are also
# returned by sysinfo(2); as such we assume they are always there.
total = mems[b'MemTotal:']
free = mems[b'MemFree:']
try:
buffers = mems[b'Buffers:']
except KeyError:
# https://github.com/giampaolo/psutil/issues/1010
buffers = 0
missing_fields.append('buffers')
try:
cached = mems[b"Cached:"]
except KeyError:
cached = 0
missing_fields.append('cached')
else:
# "free" cmdline utility sums reclaimable to cached.
# Older versions of procps used to add slab memory instead.
# This got changed in:
# https://gitlab.com/procps-ng/procps/commit/
# 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19
try:
shared = mems[b'Shmem:'] # since kernel 2.6.32
except KeyError:
try:
shared = mems[b'MemShared:'] # kernels 2.4
except KeyError:
shared = 0
missing_fields.append('shared')
try:
active = mems[b"Active:"]
except KeyError:
active = 0
missing_fields.append('active')
try:
inactive = mems[b"Inactive:"]
except KeyError:
try:
inactive = \
mems[b"Inact_dirty:"] + \
mems[b"Inact_clean:"] + \
mems[b"Inact_laundry:"]
except KeyError:
inactive = 0
missing_fields.append('inactive')
try:
slab = mems[b"Slab:"]
except KeyError:
slab = 0
used = total - free - cached - buffers
if used < 0:
# May be symptomatic of running within a LCX container where such
# values will be dramatically distorted over those of the host.
used = total - free
# - starting from 4.4.0 we match free's "available" column.
# Before 4.4.0 we calculated it as (free + buffers + cached)
# which matched htop.
# - free and htop available memory differs as per:
# http://askubuntu.com/a/369589
# http://unix.stackexchange.com/a/65852/168884
# - MemAvailable has been introduced in kernel 3.14
try:
avail = mems[b'MemAvailable:']
except KeyError:
avail = calculate_avail_vmem(mems)
else:
if avail == 0:
# Yes, it can happen (probably a kernel bug):
# https://github.com/giampaolo/psutil/issues/1915
# In this case "free" CLI tool makes an estimate. We do the same,
# and it matches "free" CLI tool.
avail = calculate_avail_vmem(mems)
if avail < 0:
avail = 0
missing_fields.append('available')
elif avail > total:
# If avail is greater than total or our calculation overflows,
# that's symptomatic of running within a LCX container where such
# values will be dramatically distorted over those of the host.
# https://gitlab.com/procps-ng/procps/blob/
# 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764
avail = free
percent = usage_percent((total - avail), total, round_=1)
# Warn about missing metrics which are set to 0.
if missing_fields:
msg = "%s memory stats couldn't be determined and %s set to 0" % (
", ".join(missing_fields),
"was" if len(missing_fields) == 1 else "were")
warnings.warn(msg, RuntimeWarning, stacklevel=2)
return svmem(total, avail, percent, used, free,
active, inactive, buffers, cached, shared, slab)
def swap_memory():
"""Return swap memory metrics."""
mems = {}
with open_binary('%s/meminfo' % get_procfs_path()) as f:
for line in f:
fields = line.split()
mems[fields[0]] = int(fields[1]) * 1024
# We prefer /proc/meminfo over sysinfo() syscall so that
# psutil.PROCFS_PATH can be used in order to allow retrieval
# for linux containers, see:
# https://github.com/giampaolo/psutil/issues/1015
try:
total = mems[b'SwapTotal:']
free = mems[b'SwapFree:']
except KeyError:
_, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
total *= unit_multiplier
free *= unit_multiplier
used = total - free
percent = usage_percent(used, total, round_=1)
# get pgin/pgouts
try:
f = open_binary("%s/vmstat" % get_procfs_path())
except IOError as err:
# see https://github.com/giampaolo/psutil/issues/722
msg = "'sin' and 'sout' swap memory stats couldn't " \
"be determined and were set to 0 (%s)" % str(err)
warnings.warn(msg, RuntimeWarning, stacklevel=2)
sin = sout = 0
else:
with f:
sin = sout = None
for line in f:
# values are expressed in 4 kilo bytes, we want
# bytes instead
if line.startswith(b'pswpin'):
sin = int(line.split(b' ')[1]) * 4 * 1024
elif line.startswith(b'pswpout'):
sout = int(line.split(b' ')[1]) * 4 * 1024
if sin is not None and sout is not None:
break
else:
# we might get here when dealing with exotic Linux
# flavors, see:
# https://github.com/giampaolo/psutil/issues/313
msg = "'sin' and 'sout' swap memory stats couldn't " \
"be determined and were set to 0"
warnings.warn(msg, RuntimeWarning, stacklevel=2)
sin = sout = 0
return _common.sswap(total, used, free, percent, sin, sout)
# =====================================================================
# --- CPU
# =====================================================================
def cpu_times():
"""Return a named tuple representing the following system-wide
CPU times:
(user, nice, system, idle, iowait, irq, softirq [steal, [guest,
[guest_nice]]])
Last 3 fields may not be available on all Linux kernel versions.
"""
procfs_path = get_procfs_path()
set_scputimes_ntuple(procfs_path)
with open_binary('%s/stat' % procfs_path) as f:
values = f.readline().split()
fields = values[1:len(scputimes._fields) + 1]
fields = [float(x) / CLOCK_TICKS for x in fields]
return scputimes(*fields)
def per_cpu_times():
"""Return a list of namedtuple representing the CPU times
for every CPU available on the system.
"""
procfs_path = get_procfs_path()
set_scputimes_ntuple(procfs_path)
cpus = []
with open_binary('%s/stat' % procfs_path) as f:
# get rid of the first line which refers to system wide CPU stats
f.readline()
for line in f:
if line.startswith(b'cpu'):
values = line.split()
fields = values[1:len(scputimes._fields) + 1]
fields = [float(x) / CLOCK_TICKS for x in fields]
entry = scputimes(*fields)
cpus.append(entry)
return cpus
def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
# as a second fallback we try to parse /proc/cpuinfo
num = 0
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
for line in f:
if line.lower().startswith(b'processor'):
num += 1
# unknown format (e.g. amrel/sparc architectures), see:
# https://github.com/giampaolo/psutil/issues/200
# try to parse /proc/stat as a last resort
if num == 0:
search = re.compile(r'cpu\d')
with open_text('%s/stat' % get_procfs_path()) as f:
for line in f:
line = line.split(' ')[0]
if search.match(line):
num += 1
if num == 0:
# mimic os.cpu_count()
return None
return num
def cpu_count_cores():
"""Return the number of CPU cores in the system."""
# Method #1
ls = set()
# These 2 files are the same but */core_cpus_list is newer while
# */thread_siblings_list is deprecated and may disappear in the future.
# https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst
# https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964
# https://lkml.org/lkml/2019/2/26/41
p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list"
p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"
for path in glob.glob(p1) or glob.glob(p2):
with open_binary(path) as f:
ls.add(f.read().strip())
result = len(ls)
if result != 0:
return result
# Method #2
mapping = {}
current_info = {}
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
for line in f:
line = line.strip().lower()
if not line:
# new section
try:
mapping[current_info[b'physical id']] = \
current_info[b'cpu cores']
except KeyError:
pass
current_info = {}
else:
# ongoing section
if line.startswith((b'physical id', b'cpu cores')):
key, value = line.split(b'\t:', 1)
current_info[key] = int(value)
result = sum(mapping.values())
return result or None # mimic os.cpu_count()
def cpu_stats():
"""Return various CPU stats as a named tuple."""
with open_binary('%s/stat' % get_procfs_path()) as f:
ctx_switches = None
interrupts = None
soft_interrupts = None
for line in f:
if line.startswith(b'ctxt'):
ctx_switches = int(line.split()[1])
elif line.startswith(b'intr'):
interrupts = int(line.split()[1])
elif line.startswith(b'softirq'):
soft_interrupts = int(line.split()[1])
if ctx_switches is not None and soft_interrupts is not None \
and interrupts is not None:
break
syscalls = 0
return _common.scpustats(
ctx_switches, interrupts, soft_interrupts, syscalls)
def _cpu_get_cpuinfo_freq():
"""Return current CPU frequency from cpuinfo if available.
"""
ret = []
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
for line in f:
if line.lower().startswith(b'cpu mhz'):
ret.append(float(line.split(b':', 1)[1]))
return ret
if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \
os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"):
def cpu_freq():
"""Return frequency metrics for all CPUs.
Contrarily to other OSes, Linux updates these values in
real-time.
"""
cpuinfo_freqs = _cpu_get_cpuinfo_freq()
paths = \
glob.glob("/sys/devices/system/cpu/cpufreq/policy[0-9]*") or \
glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq")
paths.sort(key=lambda x: int(re.search(r"[0-9]+", x).group()))
ret = []
pjoin = os.path.join
for i, path in enumerate(paths):
if len(paths) == len(cpuinfo_freqs):
# take cached value from cpuinfo if available, see:
# https://github.com/giampaolo/psutil/issues/1851
curr = cpuinfo_freqs[i] * 1000
else:
curr = bcat(pjoin(path, "scaling_cur_freq"), fallback=None)
if curr is None:
# Likely an old RedHat, see:
# https://github.com/giampaolo/psutil/issues/1071
curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
if curr is None:
raise NotImplementedError(
"can't find current frequency file")
curr = int(curr) / 1000
max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000
min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000
ret.append(_common.scpufreq(curr, min_, max_))
return ret
else:
def cpu_freq():
"""Alternate implementation using /proc/cpuinfo.
min and max frequencies are not available and are set to None.
"""
return [_common.scpufreq(x, 0., 0.) for x in _cpu_get_cpuinfo_freq()]
# =====================================================================
# --- network
# =====================================================================
net_if_addrs = cext_posix.net_if_addrs
class _Ipv6UnsupportedError(Exception):
pass
class Connections:
"""A wrapper on top of /proc/net/* files, retrieving per-process
and system-wide open connections (TCP, UDP, UNIX) similarly to
"netstat -an".
Note: in case of UNIX sockets we're only able to determine the
local endpoint/path, not the one it's connected to.
According to [1] it would be possible but not easily.
[1] http://serverfault.com/a/417946
"""
def __init__(self):
# The string represents the basename of the corresponding
# /proc/net/{proto_name} file.
tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
unix = ("unix", socket.AF_UNIX, None)
self.tmap = {
"all": (tcp4, tcp6, udp4, udp6, unix),
"tcp": (tcp4, tcp6),
"tcp4": (tcp4,),
"tcp6": (tcp6,),
"udp": (udp4, udp6),
"udp4": (udp4,),
"udp6": (udp6,),
"unix": (unix,),
"inet": (tcp4, tcp6, udp4, udp6),
"inet4": (tcp4, udp4),
"inet6": (tcp6, udp6),
}
self._procfs_path = None
def get_proc_inodes(self, pid):
inodes = defaultdict(list)
for fd in os.listdir("%s/%s/fd" % (self._procfs_path, pid)):
try:
inode = readlink("%s/%s/fd/%s" % (self._procfs_path, pid, fd))
except (FileNotFoundError, ProcessLookupError):
# ENOENT == file which is gone in the meantime;
# os.stat('/proc/%s' % self.pid) will be done later
# to force NSP (if it's the case)
continue
except OSError as err:
if err.errno == errno.EINVAL:
# not a link
continue
if err.errno == errno.ENAMETOOLONG:
# file name too long
debug(err)
continue
raise
else:
if inode.startswith('socket:['):
# the process is using a socket
inode = inode[8:][:-1]
inodes[inode].append((pid, int(fd)))
return inodes
def get_all_inodes(self):
inodes = {}
for pid in pids():
try:
inodes.update(self.get_proc_inodes(pid))
except (FileNotFoundError, ProcessLookupError, PermissionError):
# os.listdir() is gonna raise a lot of access denied
# exceptions in case of unprivileged user; that's fine
# as we'll just end up returning a connection with PID
# and fd set to None anyway.
# Both netstat -an and lsof does the same so it's
# unlikely we can do any better.
# ENOENT just means a PID disappeared on us.
continue
return inodes
@staticmethod
def decode_address(addr, family):
"""Accept an "ip:port" address as displayed in /proc/net/*
and convert it into a human readable form, like:
"0500000A:0016" -> ("10.0.0.5", 22)
"0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
The IP address portion is a little or big endian four-byte
hexadecimal number; that is, the least significant byte is listed
first, so we need to reverse the order of the bytes to convert it
to an IP address.
The port is represented as a two-byte hexadecimal number.
Reference:
http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
"""
ip, port = addr.split(':')
port = int(port, 16)
# this usually refers to a local socket in listen mode with
# no end-points connected
if not port:
return ()
if PY3:
ip = ip.encode('ascii')
if family == socket.AF_INET:
# see: https://github.com/giampaolo/psutil/issues/201
if LITTLE_ENDIAN:
ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
else:
ip = socket.inet_ntop(family, base64.b16decode(ip))
else: # IPv6
ip = base64.b16decode(ip)
try:
# see: https://github.com/giampaolo/psutil/issues/201
if LITTLE_ENDIAN:
ip = socket.inet_ntop(
socket.AF_INET6,
struct.pack('>4I', *struct.unpack('<4I', ip)))
else:
ip = socket.inet_ntop(
socket.AF_INET6,
struct.pack('<4I', *struct.unpack('<4I', ip)))
except ValueError:
# see: https://github.com/giampaolo/psutil/issues/623
if not supports_ipv6():
raise _Ipv6UnsupportedError
else:
raise
return _common.addr(ip, port)
@staticmethod
def process_inet(file, family, type_, inodes, filter_pid=None):
"""Parse /proc/net/tcp* and /proc/net/udp* files."""
if file.endswith('6') and not os.path.exists(file):
# IPv6 not supported
return
with open_text(file) as f:
f.readline() # skip the first line
for lineno, line in enumerate(f, 1):
try:
_, laddr, raddr, status, _, _, _, _, _, inode = \
line.split()[:10]
except ValueError:
raise RuntimeError(
"error while parsing %s; malformed line %s %r" % (
file, lineno, line))
if inode in inodes:
# # We assume inet sockets are unique, so we error
# # out if there are multiple references to the
# # same inode. We won't do this for UNIX sockets.
# if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
# raise ValueError("ambiguous inode with multiple "
# "PIDs references")
pid, fd = inodes[inode][0]
else:
pid, fd = None, -1
if filter_pid is not None and filter_pid != pid:
continue
else:
if type_ == socket.SOCK_STREAM:
status = TCP_STATUSES[status]
else:
status = _common.CONN_NONE
try:
laddr = Connections.decode_address(laddr, family)
raddr = Connections.decode_address(raddr, family)
except _Ipv6UnsupportedError:
continue
yield (fd, family, type_, laddr, raddr, status, pid)
@staticmethod
def process_unix(file, family, inodes, filter_pid=None):
"""Parse /proc/net/unix files."""
with open_text(file) as f:
f.readline() # skip the first line
for line in f:
tokens = line.split()
try:
_, _, _, _, type_, _, inode = tokens[0:7]
except ValueError:
if ' ' not in line:
# see: https://github.com/giampaolo/psutil/issues/766
continue
raise RuntimeError(
"error while parsing %s; malformed line %r" % (
file, line))
if inode in inodes:
# With UNIX sockets we can have a single inode
# referencing many file descriptors.
pairs = inodes[inode]
else:
pairs = [(None, -1)]
for pid, fd in pairs:
if filter_pid is not None and filter_pid != pid:
continue
else:
if len(tokens) == 8:
path = tokens[-1]
else:
path = ""
type_ = _common.socktype_to_enum(int(type_))
# XXX: determining the remote endpoint of a
# UNIX socket on Linux is not possible, see:
# https://serverfault.com/questions/252723/
raddr = ""
status = _common.CONN_NONE
yield (fd, family, type_, path, raddr, status, pid)
def retrieve(self, kind, pid=None):
if kind not in self.tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in self.tmap])))
self._procfs_path = get_procfs_path()
if pid is not None:
inodes = self.get_proc_inodes(pid)
if not inodes:
# no connections for this process
return []
else:
inodes = self.get_all_inodes()
ret = set()
for proto_name, family, type_ in self.tmap[kind]:
path = "%s/net/%s" % (self._procfs_path, proto_name)
if family in (socket.AF_INET, socket.AF_INET6):
ls = self.process_inet(
path, family, type_, inodes, filter_pid=pid)
else:
ls = self.process_unix(
path, family, inodes, filter_pid=pid)
for fd, family, type_, laddr, raddr, status, bound_pid in ls:
if pid:
conn = _common.pconn(fd, family, type_, laddr, raddr,
status)
else:
conn = _common.sconn(fd, family, type_, laddr, raddr,
status, bound_pid)
ret.add(conn)
return list(ret)
_connections = Connections()
def net_connections(kind='inet'):
"""Return system-wide open connections."""
return _connections.retrieve(kind)
def net_io_counters():
"""Return network I/O statistics for every network interface
installed on the system as a dict of raw tuples.
"""
with open_text("%s/net/dev" % get_procfs_path()) as f:
lines = f.readlines()
retdict = {}
for line in lines[2:]:
colon = line.rfind(':')
assert colon > 0, repr(line)
name = line[:colon].strip()
fields = line[colon + 1:].strip().split()
# in
(bytes_recv,
packets_recv,
errin,
dropin,
fifoin, # unused
framein, # unused
compressedin, # unused
multicastin, # unused
# out
bytes_sent,
packets_sent,
errout,
dropout,
fifoout, # unused
collisionsout, # unused
carrierout, # unused
compressedout) = map(int, fields)
retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv,
errin, errout, dropin, dropout)
return retdict
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
duplex_map = {cext.DUPLEX_FULL: NIC_DUPLEX_FULL,
cext.DUPLEX_HALF: NIC_DUPLEX_HALF,
cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN}
names = net_io_counters().keys()
ret = {}
for name in names:
try:
mtu = cext_posix.net_if_mtu(name)
flags = cext_posix.net_if_flags(name)
duplex, speed = cext.net_if_duplex_speed(name)
except OSError as err:
# https://github.com/giampaolo/psutil/issues/1279
if err.errno != errno.ENODEV:
raise
else:
debug(err)
else:
output_flags = ','.join(flags)
isup = 'running' in flags
ret[name] = _common.snicstats(isup, duplex_map[duplex], speed, mtu,
output_flags)
return ret
# =====================================================================
# --- disks
# =====================================================================
disk_usage = _psposix.disk_usage
def disk_io_counters(perdisk=False):
"""Return disk I/O statistics for every disk installed on the
system as a dict of raw tuples.
"""
def read_procfs():
# OK, this is a bit confusing. The format of /proc/diskstats can
# have 3 variations.
# On Linux 2.4 each line has always 15 fields, e.g.:
# "3 0 8 hda 8 8 8 8 8 8 8 8 8 8 8"
# On Linux 2.6+ each line *usually* has 14 fields, and the disk
# name is in another position, like this:
# "3 0 hda 8 8 8 8 8 8 8 8 8 8 8"
# ...unless (Linux 2.6) the line refers to a partition instead
# of a disk, in which case the line has less fields (7):
# "3 1 hda1 8 8 8 8"
# 4.18+ has 4 fields added:
# "3 0 hda 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0"
# 5.5 has 2 more fields.
# See:
# https://www.kernel.org/doc/Documentation/iostats.txt
# https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
with open_text("%s/diskstats" % get_procfs_path()) as f:
lines = f.readlines()
for line in lines:
fields = line.split()
flen = len(fields)
if flen == 15:
# Linux 2.4
name = fields[3]
reads = int(fields[2])
(reads_merged, rbytes, rtime, writes, writes_merged,
wbytes, wtime, _, busy_time, _) = map(int, fields[4:14])
elif flen == 14 or flen >= 18:
# Linux 2.6+, line referring to a disk
name = fields[2]
(reads, reads_merged, rbytes, rtime, writes, writes_merged,
wbytes, wtime, _, busy_time, _) = map(int, fields[3:14])
elif flen == 7:
# Linux 2.6+, line referring to a partition
name = fields[2]
reads, rbytes, writes, wbytes = map(int, fields[3:])
rtime = wtime = reads_merged = writes_merged = busy_time = 0
else:
raise ValueError("not sure how to interpret line %r" % line)
yield (name, reads, writes, rbytes, wbytes, rtime, wtime,
reads_merged, writes_merged, busy_time)
def read_sysfs():
for block in os.listdir('/sys/block'):
for root, _, files in os.walk(os.path.join('/sys/block', block)):
if 'stat' not in files:
continue
with open_text(os.path.join(root, 'stat')) as f:
fields = f.read().strip().split()
name = os.path.basename(root)
(reads, reads_merged, rbytes, rtime, writes, writes_merged,
wbytes, wtime, _, busy_time) = map(int, fields[:10])
yield (name, reads, writes, rbytes, wbytes, rtime,
wtime, reads_merged, writes_merged, busy_time)
if os.path.exists('%s/diskstats' % get_procfs_path()):
gen = read_procfs()
elif os.path.exists('/sys/block'):
gen = read_sysfs()
else:
raise NotImplementedError(
"%s/diskstats nor /sys/block filesystem are available on this "
"system" % get_procfs_path())
retdict = {}
for entry in gen:
(name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged,
writes_merged, busy_time) = entry
if not perdisk and not is_storage_device(name):
# perdisk=False means we want to calculate totals so we skip
# partitions (e.g. 'sda1', 'nvme0n1p1') and only include
# base disk devices (e.g. 'sda', 'nvme0n1'). Base disks
# include a total of all their partitions + some extra size
# of their own:
# $ cat /proc/diskstats
# 259 0 sda 10485760 ...
# 259 1 sda1 5186039 ...
# 259 1 sda2 5082039 ...
# See:
# https://github.com/giampaolo/psutil/pull/1313
continue
rbytes *= DISK_SECTOR_SIZE
wbytes *= DISK_SECTOR_SIZE
retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime,
reads_merged, writes_merged, busy_time)
return retdict
class RootFsDeviceFinder:
"""disk_partitions() may return partitions with device == "/dev/root"
or "rootfs". This container class uses different strategies to try to
obtain the real device path. Resources:
https://bootlin.com/blog/find-root-device/
https://www.systutorials.com/how-to-find-the-disk-where-root-is-on-in-bash-on-linux/
"""
__slots__ = ['major', 'minor']
def __init__(self):
dev = os.stat("/").st_dev
self.major = os.major(dev)
self.minor = os.minor(dev)
def ask_proc_partitions(self):
with open_text("%s/partitions" % get_procfs_path()) as f:
for line in f.readlines()[2:]:
fields = line.split()
if len(fields) < 4: # just for extra safety
continue
major = int(fields[0]) if fields[0].isdigit() else None
minor = int(fields[1]) if fields[1].isdigit() else None
name = fields[3]
if major == self.major and minor == self.minor:
if name: # just for extra safety
return "/dev/%s" % name
def ask_sys_dev_block(self):
path = "/sys/dev/block/%s:%s/uevent" % (self.major, self.minor)
with open_text(path) as f:
for line in f:
if line.startswith("DEVNAME="):
name = line.strip().rpartition("DEVNAME=")[2]
if name: # just for extra safety
return "/dev/%s" % name
def ask_sys_class_block(self):
needle = "%s:%s" % (self.major, self.minor)
files = glob.iglob("/sys/class/block/*/dev")
for file in files:
try:
f = open_text(file)
except FileNotFoundError: # race condition
continue
else:
with f:
data = f.read().strip()
if data == needle:
name = os.path.basename(os.path.dirname(file))
return "/dev/%s" % name
def find(self):
path = None
if path is None:
try:
path = self.ask_proc_partitions()
except (IOError, OSError) as err:
debug(err)
if path is None:
try:
path = self.ask_sys_dev_block()
except (IOError, OSError) as err:
debug(err)
if path is None:
try:
path = self.ask_sys_class_block()
except (IOError, OSError) as err:
debug(err)
# We use exists() because the "/dev/*" part of the path is hard
# coded, so we want to be sure.
if path is not None and os.path.exists(path):
return path
def disk_partitions(all=False):
"""Return mounted disk partitions as a list of namedtuples."""
fstypes = set()
procfs_path = get_procfs_path()
if not all:
with open_text("%s/filesystems" % procfs_path) as f:
for line in f:
line = line.strip()
if not line.startswith("nodev"):
fstypes.add(line.strip())
else:
# ignore all lines starting with "nodev" except "nodev zfs"
fstype = line.split("\t")[1]
if fstype == "zfs":
fstypes.add("zfs")
# See: https://github.com/giampaolo/psutil/issues/1307
if procfs_path == "/proc" and os.path.isfile('/etc/mtab'):
mounts_path = os.path.realpath("/etc/mtab")
else:
mounts_path = os.path.realpath("%s/self/mounts" % procfs_path)
retlist = []
partitions = cext.disk_partitions(mounts_path)
for partition in partitions:
device, mountpoint, fstype, opts = partition
if device == 'none':
device = ''
if device in ("/dev/root", "rootfs"):
device = RootFsDeviceFinder().find() or device
if not all:
if device == '' or fstype not in fstypes:
continue
maxfile = maxpath = None # set later
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts,
maxfile, maxpath)
retlist.append(ntuple)
return retlist
# =====================================================================
# --- sensors
# =====================================================================
def sensors_temperatures():
"""Return hardware (CPU and others) temperatures as a dict
including hardware name, label, current, max and critical
temperatures.
Implementation notes:
- /sys/class/hwmon looks like the most recent interface to
retrieve this info, and this implementation relies on it
only (old distros will probably use something else)
- lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
- /sys/class/thermal/thermal_zone* is another one but it's more
difficult to parse
"""
ret = collections.defaultdict(list)
basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*')
# CentOS has an intermediate /device directory:
# https://github.com/giampaolo/psutil/issues/971
# https://github.com/nicolargo/glances/issues/1060
basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*'))
basenames = sorted(set([x.split('_')[0] for x in basenames]))
# Only add the coretemp hwmon entries if they're not already in
# /sys/class/hwmon/
# https://github.com/giampaolo/psutil/issues/1708
# https://github.com/giampaolo/psutil/pull/1648
basenames2 = glob.glob(
'/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*')
repl = re.compile('/sys/devices/platform/coretemp.*/hwmon/')
for name in basenames2:
altname = repl.sub('/sys/class/hwmon/', name)
if altname not in basenames:
basenames.append(name)
for base in basenames:
try:
path = base + '_input'
current = float(bcat(path)) / 1000.0
path = os.path.join(os.path.dirname(base), 'name')
unit_name = cat(path).strip()
except (IOError, OSError, ValueError):
# A lot of things can go wrong here, so let's just skip the
# whole entry. Sure thing is Linux's /sys/class/hwmon really
# is a stinky broken mess.
# https://github.com/giampaolo/psutil/issues/1009
# https://github.com/giampaolo/psutil/issues/1101
# https://github.com/giampaolo/psutil/issues/1129
# https://github.com/giampaolo/psutil/issues/1245
# https://github.com/giampaolo/psutil/issues/1323
continue
high = bcat(base + '_max', fallback=None)
critical = bcat(base + '_crit', fallback=None)
label = cat(base + '_label', fallback='').strip()
if high is not None:
try:
high = float(high) / 1000.0
except ValueError:
high = None
if critical is not None:
try:
critical = float(critical) / 1000.0
except ValueError:
critical = None
ret[unit_name].append((label, current, high, critical))
# Indication that no sensors were detected in /sys/class/hwmon/
if not basenames:
basenames = glob.glob('/sys/class/thermal/thermal_zone*')
basenames = sorted(set(basenames))
for base in basenames:
try:
path = os.path.join(base, 'temp')
current = float(bcat(path)) / 1000.0
path = os.path.join(base, 'type')
unit_name = cat(path).strip()
except (IOError, OSError, ValueError) as err:
debug(err)
continue
trip_paths = glob.glob(base + '/trip_point*')
trip_points = set(['_'.join(
os.path.basename(p).split('_')[0:3]) for p in trip_paths])
critical = None
high = None
for trip_point in trip_points:
path = os.path.join(base, trip_point + "_type")
trip_type = cat(path, fallback='').strip()
if trip_type == 'critical':
critical = bcat(os.path.join(base, trip_point + "_temp"),
fallback=None)
elif trip_type == 'high':
high = bcat(os.path.join(base, trip_point + "_temp"),
fallback=None)
if high is not None:
try:
high = float(high) / 1000.0
except ValueError:
high = None
if critical is not None:
try:
critical = float(critical) / 1000.0
except ValueError:
critical = None
ret[unit_name].append(('', current, high, critical))
return dict(ret)
def sensors_fans():
"""Return hardware fans info (for CPU and other peripherals) as a
dict including hardware label and current speed.
Implementation notes:
- /sys/class/hwmon looks like the most recent interface to
retrieve this info, and this implementation relies on it
only (old distros will probably use something else)
- lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
"""
ret = collections.defaultdict(list)
basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
if not basenames:
# CentOS has an intermediate /device directory:
# https://github.com/giampaolo/psutil/issues/971
basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*')
basenames = sorted(set([x.split('_')[0] for x in basenames]))
for base in basenames:
try:
current = int(bcat(base + '_input'))
except (IOError, OSError) as err:
debug(err)
continue
unit_name = cat(os.path.join(os.path.dirname(base), 'name')).strip()
label = cat(base + '_label', fallback='').strip()
ret[unit_name].append(_common.sfan(label, current))
return dict(ret)
def sensors_battery():
"""Return battery information.
Implementation note: it appears /sys/class/power_supply/BAT0/
directory structure may vary and provide files with the same
meaning but under different names, see:
https://github.com/giampaolo/psutil/issues/966
"""
null = object()
def multi_bcat(*paths):
"""Attempt to read the content of multiple files which may
not exist. If none of them exist return None.
"""
for path in paths:
ret = bcat(path, fallback=null)
if ret != null:
try:
return int(ret)
except ValueError:
return ret.strip()
return None
bats = [x for x in os.listdir(POWER_SUPPLY_PATH) if x.startswith('BAT') or
'battery' in x.lower()]
if not bats:
return None
# Get the first available battery. Usually this is "BAT0", except
# some rare exceptions:
# https://github.com/giampaolo/psutil/issues/1238
root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0])
# Base metrics.
energy_now = multi_bcat(
root + "/energy_now",
root + "/charge_now")
power_now = multi_bcat(
root + "/power_now",
root + "/current_now")
energy_full = multi_bcat(
root + "/energy_full",
root + "/charge_full")
time_to_empty = multi_bcat(root + "/time_to_empty_now")
# Percent. If we have energy_full the percentage will be more
# accurate compared to reading /capacity file (float vs. int).
if energy_full is not None and energy_now is not None:
try:
percent = 100.0 * energy_now / energy_full
except ZeroDivisionError:
percent = 0.0
else:
percent = int(cat(root + "/capacity", fallback=-1))
if percent == -1:
return None
# Is AC power cable plugged in?
# Note: AC0 is not always available and sometimes (e.g. CentOS7)
# it's called "AC".
power_plugged = None
online = multi_bcat(
os.path.join(POWER_SUPPLY_PATH, "AC0/online"),
os.path.join(POWER_SUPPLY_PATH, "AC/online"))
if online is not None:
power_plugged = online == 1
else:
status = cat(root + "/status", fallback="").strip().lower()
if status == "discharging":
power_plugged = False
elif status in ("charging", "full"):
power_plugged = True
# Seconds left.
# Note to self: we may also calculate the charging ETA as per:
# https://github.com/thialfihar/dotfiles/blob/
# 013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55
if power_plugged:
secsleft = _common.POWER_TIME_UNLIMITED
elif energy_now is not None and power_now is not None:
try:
secsleft = int(energy_now / power_now * 3600)
except ZeroDivisionError:
secsleft = _common.POWER_TIME_UNKNOWN
elif time_to_empty is not None:
secsleft = int(time_to_empty * 60)
if secsleft < 0:
secsleft = _common.POWER_TIME_UNKNOWN
else:
secsleft = _common.POWER_TIME_UNKNOWN
return _common.sbattery(percent, secsleft, power_plugged)
# =====================================================================
# --- other system functions
# =====================================================================
def users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = cext.users()
for item in rawlist:
user, tty, hostname, tstamp, user_process, pid = item
# note: the underlying C function includes entries about
# system boot, run level and others. We might want
# to use them in the future.
if not user_process:
continue
if hostname in (':0.0', ':0'):
hostname = 'localhost'
nt = _common.suser(user, tty or None, hostname, tstamp, pid)
retlist.append(nt)
return retlist
def boot_time():
"""Return the system boot time expressed in seconds since the epoch."""
global BOOT_TIME
path = '%s/stat' % get_procfs_path()
with open_binary(path) as f:
for line in f:
if line.startswith(b'btime'):
ret = float(line.strip().split()[1])
BOOT_TIME = ret
return ret
raise RuntimeError(
"line 'btime' not found in %s" % path)
# =====================================================================
# --- processes
# =====================================================================
def pids():
"""Returns a list of PIDs currently running on the system."""
return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
def pid_exists(pid):
"""Check for the existence of a unix PID. Linux TIDs are not
supported (always return False).
"""
if not _psposix.pid_exists(pid):
return False
else:
# Linux's apparently does not distinguish between PIDs and TIDs
# (thread IDs).
# listdir("/proc") won't show any TID (only PIDs) but
# os.stat("/proc/{tid}") will succeed if {tid} exists.
# os.kill() can also be passed a TID. This is quite confusing.
# In here we want to enforce this distinction and support PIDs
# only, see:
# https://github.com/giampaolo/psutil/issues/687
try:
# Note: already checked that this is faster than using a
# regular expr. Also (a lot) faster than doing
# 'return pid in pids()'
path = "%s/%s/status" % (get_procfs_path(), pid)
with open_binary(path) as f:
for line in f:
if line.startswith(b"Tgid:"):
tgid = int(line.split()[1])
# If tgid and pid are the same then we're
# dealing with a process PID.
return tgid == pid
raise ValueError("'Tgid' line not found in %s" % path)
except (EnvironmentError, ValueError):
return pid in pids()
def ppid_map():
"""Obtain a {pid: ppid, ...} dict for all running processes in
one shot. Used to speed up Process.children().
"""
ret = {}
procfs_path = get_procfs_path()
for pid in pids():
try:
with open_binary("%s/%s/stat" % (procfs_path, pid)) as f:
data = f.read()
except (FileNotFoundError, ProcessLookupError):
# Note: we should be able to access /stat for all processes
# aka it's unlikely we'll bump into EPERM, which is good.
pass
else:
rpar = data.rfind(b')')
dset = data[rpar + 2:].split()
ppid = int(dset[1])
ret[pid] = ppid
return ret
def wrap_exceptions(fun):
"""Decorator which translates bare OSError and IOError exceptions
into NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except PermissionError:
raise AccessDenied(self.pid, self._name)
except ProcessLookupError:
raise NoSuchProcess(self.pid, self._name)
except FileNotFoundError:
if not os.path.exists("%s/%s" % (self._procfs_path, self.pid)):
raise NoSuchProcess(self.pid, self._name)
# Note: zombies will keep existing under /proc until they're
# gone so there's no way to distinguish them in here.
raise
return wrapper
class Process(object):
"""Linux process implementation."""
__slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
def __init__(self, pid):
self.pid = pid
self._name = None
self._ppid = None
self._procfs_path = get_procfs_path()
def _assert_alive(self):
"""Raise NSP if the process disappeared on us."""
# For those C function who do not raise NSP, possibly returning
# incorrect or incomplete result.
os.stat('%s/%s' % (self._procfs_path, self.pid))
@wrap_exceptions
@memoize_when_activated
def _parse_stat_file(self):
"""Parse /proc/{pid}/stat file and return a dict with various
process info.
Using "man proc" as a reference: where "man proc" refers to
position N always subtract 3 (e.g ppid position 4 in
'man proc' == position 1 in here).
The return value is cached in case oneshot() ctx manager is
in use.
"""
data = bcat("%s/%s/stat" % (self._procfs_path, self.pid))
# Process name is between parentheses. It can contain spaces and
# other parentheses. This is taken into account by looking for
# the first occurrence of "(" and the last occurrence of ")".
rpar = data.rfind(b')')
name = data[data.find(b'(') + 1:rpar]
fields = data[rpar + 2:].split()
ret = {}
ret['name'] = name
ret['status'] = fields[0]
ret['ppid'] = fields[1]
ret['ttynr'] = fields[4]
ret['utime'] = fields[11]
ret['stime'] = fields[12]
ret['children_utime'] = fields[13]
ret['children_stime'] = fields[14]
ret['create_time'] = fields[19]
ret['cpu_num'] = fields[36]
ret['blkio_ticks'] = fields[39] # aka 'delayacct_blkio_ticks'
return ret
@wrap_exceptions
@memoize_when_activated
def _read_status_file(self):
"""Read /proc/{pid}/stat file and return its content.
The return value is cached in case oneshot() ctx manager is
in use.
"""
with open_binary("%s/%s/status" % (self._procfs_path, self.pid)) as f:
return f.read()
@wrap_exceptions
@memoize_when_activated
def _read_smaps_file(self):
with open_binary("%s/%s/smaps" % (self._procfs_path, self.pid)) as f:
return f.read().strip()
def oneshot_enter(self):
self._parse_stat_file.cache_activate(self)
self._read_status_file.cache_activate(self)
self._read_smaps_file.cache_activate(self)
def oneshot_exit(self):
self._parse_stat_file.cache_deactivate(self)
self._read_status_file.cache_deactivate(self)
self._read_smaps_file.cache_deactivate(self)
@wrap_exceptions
def name(self):
name = self._parse_stat_file()['name']
if PY3:
name = decode(name)
# XXX - gets changed later and probably needs refactoring
return name
def exe(self):
try:
return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
except (FileNotFoundError, ProcessLookupError):
# no such file error; might be raised also if the
# path actually exists for system processes with
# low pids (about 0-20)
if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
return ""
else:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
except PermissionError:
raise AccessDenied(self.pid, self._name)
@wrap_exceptions
def cmdline(self):
with open_text("%s/%s/cmdline" % (self._procfs_path, self.pid)) as f:
data = f.read()
if not data:
# may happen in case of zombie process
return []
# 'man proc' states that args are separated by null bytes '\0'
# and last char is supposed to be a null byte. Nevertheless
# some processes may change their cmdline after being started
# (via setproctitle() or similar), they are usually not
# compliant with this rule and use spaces instead. Google
# Chrome process is an example. See:
# https://github.com/giampaolo/psutil/issues/1179
sep = '\x00' if data.endswith('\x00') else ' '
if data.endswith(sep):
data = data[:-1]
cmdline = data.split(sep)
# Sometimes last char is a null byte '\0' but the args are
# separated by spaces, see: https://github.com/giampaolo/psutil/
# issues/1179#issuecomment-552984549
if sep == '\x00' and len(cmdline) == 1 and ' ' in data:
cmdline = data.split(' ')
return cmdline
@wrap_exceptions
def environ(self):
with open_text("%s/%s/environ" % (self._procfs_path, self.pid)) as f:
data = f.read()
return parse_environ_block(data)
@wrap_exceptions
def terminal(self):
tty_nr = int(self._parse_stat_file()['ttynr'])
tmap = _psposix.get_terminal_map()
try:
return tmap[tty_nr]
except KeyError:
return None
# May not be available on old kernels.
if os.path.exists('/proc/%s/io' % os.getpid()):
@wrap_exceptions
def io_counters(self):
fname = "%s/%s/io" % (self._procfs_path, self.pid)
fields = {}
with open_binary(fname) as f:
for line in f:
# https://github.com/giampaolo/psutil/issues/1004
line = line.strip()
if line:
try:
name, value = line.split(b': ')
except ValueError:
# https://github.com/giampaolo/psutil/issues/1004
continue
else:
fields[name] = int(value)
if not fields:
raise RuntimeError("%s file was empty" % fname)
try:
return pio(
fields[b'syscr'], # read syscalls
fields[b'syscw'], # write syscalls
fields[b'read_bytes'], # read bytes
fields[b'write_bytes'], # write bytes
fields[b'rchar'], # read chars
fields[b'wchar'], # write chars
)
except KeyError as err:
raise ValueError("%r field was not found in %s; found fields "
"are %r" % (err.args[0], fname, fields))
@wrap_exceptions
def cpu_times(self):
values = self._parse_stat_file()
utime = float(values['utime']) / CLOCK_TICKS
stime = float(values['stime']) / CLOCK_TICKS
children_utime = float(values['children_utime']) / CLOCK_TICKS
children_stime = float(values['children_stime']) / CLOCK_TICKS
iowait = float(values['blkio_ticks']) / CLOCK_TICKS
return pcputimes(utime, stime, children_utime, children_stime, iowait)
@wrap_exceptions
def cpu_num(self):
"""What CPU the process is on."""
return int(self._parse_stat_file()['cpu_num'])
@wrap_exceptions
def wait(self, timeout=None):
return _psposix.wait_pid(self.pid, timeout, self._name)
@wrap_exceptions
def create_time(self):
ctime = float(self._parse_stat_file()['create_time'])
# According to documentation, starttime is in field 21 and the
# unit is jiffies (clock ticks).
# We first divide it for clock ticks and then add uptime returning
# seconds since the epoch.
# Also use cached value if available.
bt = BOOT_TIME or boot_time()
return (ctime / CLOCK_TICKS) + bt
@wrap_exceptions
def memory_info(self):
# ============================================================
# | FIELD | DESCRIPTION | AKA | TOP |
# ============================================================
# | rss | resident set size | | RES |
# | vms | total program size | size | VIRT |
# | shared | shared pages (from shared mappings) | | SHR |
# | text | text ('code') | trs | CODE |
# | lib | library (unused in Linux 2.6) | lrs | |
# | data | data + stack | drs | DATA |
# | dirty | dirty pages (unused in Linux 2.6) | dt | |
# ============================================================
with open_binary("%s/%s/statm" % (self._procfs_path, self.pid)) as f:
vms, rss, shared, text, lib, data, dirty = \
[int(x) * PAGESIZE for x in f.readline().split()[:7]]
return pmem(rss, vms, shared, text, lib, data, dirty)
if HAS_PROC_SMAPS_ROLLUP or HAS_PROC_SMAPS:
@wrap_exceptions
def _parse_smaps_rollup(self):
# /proc/pid/smaps_rollup was added to Linux in 2017. Faster
# than /proc/pid/smaps. It reports higher PSS than */smaps
# (from 1k up to 200k higher; tested against all processes).
uss = pss = swap = 0
try:
with open_binary("{}/{}/smaps_rollup".format(
self._procfs_path, self.pid)) as f:
for line in f:
if line.startswith(b"Private_"):
# Private_Clean, Private_Dirty, Private_Hugetlb
uss += int(line.split()[1]) * 1024
elif line.startswith(b"Pss:"):
pss = int(line.split()[1]) * 1024
elif line.startswith(b"Swap:"):
swap = int(line.split()[1]) * 1024
except ProcessLookupError: # happens on readline()
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
return (uss, pss, swap)
@wrap_exceptions
def _parse_smaps(
self,
# Gets Private_Clean, Private_Dirty, Private_Hugetlb.
_private_re=re.compile(br"\nPrivate.*:\s+(\d+)"),
_pss_re=re.compile(br"\nPss\:\s+(\d+)"),
_swap_re=re.compile(br"\nSwap\:\s+(\d+)")):
# /proc/pid/smaps does not exist on kernels < 2.6.14 or if
# CONFIG_MMU kernel configuration option is not enabled.
# Note: using 3 regexes is faster than reading the file
# line by line.
# XXX: on Python 3 the 2 regexes are 30% slower than on
# Python 2 though. Figure out why.
#
# You might be tempted to calculate USS by subtracting
# the "shared" value from the "resident" value in
# /proc/<pid>/statm. But at least on Linux, statm's "shared"
# value actually counts pages backed by files, which has
# little to do with whether the pages are actually shared.
# /proc/self/smaps on the other hand appears to give us the
# correct information.
smaps_data = self._read_smaps_file()
# Note: smaps file can be empty for certain processes.
# The code below will not crash though and will result to 0.
uss = sum(map(int, _private_re.findall(smaps_data))) * 1024
pss = sum(map(int, _pss_re.findall(smaps_data))) * 1024
swap = sum(map(int, _swap_re.findall(smaps_data))) * 1024
return (uss, pss, swap)
def memory_full_info(self):
if HAS_PROC_SMAPS_ROLLUP: # faster
uss, pss, swap = self._parse_smaps_rollup()
else:
uss, pss, swap = self._parse_smaps()
basic_mem = self.memory_info()
return pfullmem(*basic_mem + (uss, pss, swap))
else:
memory_full_info = memory_info
if HAS_PROC_SMAPS:
@wrap_exceptions
def memory_maps(self):
"""Return process's mapped memory regions as a list of named
tuples. Fields are explained in 'man proc'; here is an updated
(Apr 2012) version: http://goo.gl/fmebo
/proc/{PID}/smaps does not exist on kernels < 2.6.14 or if
CONFIG_MMU kernel configuration option is not enabled.
"""
def get_blocks(lines, current_block):
data = {}
for line in lines:
fields = line.split(None, 5)
if not fields[0].endswith(b':'):
# new block section
yield (current_block.pop(), data)
current_block.append(line)
else:
try:
data[fields[0]] = int(fields[1]) * 1024
except ValueError:
if fields[0].startswith(b'VmFlags:'):
# see issue #369
continue
else:
raise ValueError("don't know how to inte"
"rpret line %r" % line)
yield (current_block.pop(), data)
data = self._read_smaps_file()
# Note: smaps file can be empty for certain processes.
if not data:
return []
lines = data.split(b'\n')
ls = []
first_line = lines.pop(0)
current_block = [first_line]
for header, data in get_blocks(lines, current_block):
hfields = header.split(None, 5)
try:
addr, perms, offset, dev, inode, path = hfields
except ValueError:
addr, perms, offset, dev, inode, path = \
hfields + ['']
if not path:
path = '[anon]'
else:
if PY3:
path = decode(path)
path = path.strip()
if (path.endswith(' (deleted)') and not
path_exists_strict(path)):
path = path[:-10]
ls.append((
decode(addr), decode(perms), path,
data.get(b'Rss:', 0),
data.get(b'Size:', 0),
data.get(b'Pss:', 0),
data.get(b'Shared_Clean:', 0),
data.get(b'Shared_Dirty:', 0),
data.get(b'Private_Clean:', 0),
data.get(b'Private_Dirty:', 0),
data.get(b'Referenced:', 0),
data.get(b'Anonymous:', 0),
data.get(b'Swap:', 0)
))
return ls
@wrap_exceptions
def cwd(self):
try:
return readlink("%s/%s/cwd" % (self._procfs_path, self.pid))
except (FileNotFoundError, ProcessLookupError):
# https://github.com/giampaolo/psutil/issues/986
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
@wrap_exceptions
def num_ctx_switches(self,
_ctxsw_re=re.compile(br'ctxt_switches:\t(\d+)')):
data = self._read_status_file()
ctxsw = _ctxsw_re.findall(data)
if not ctxsw:
raise NotImplementedError(
"'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'"
"lines were not found in %s/%s/status; the kernel is "
"probably older than 2.6.23" % (
self._procfs_path, self.pid))
else:
return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1]))
@wrap_exceptions
def num_threads(self, _num_threads_re=re.compile(br'Threads:\t(\d+)')):
# Note: on Python 3 using a re is faster than iterating over file
# line by line. On Python 2 is the exact opposite, and iterating
# over a file on Python 3 is slower than on Python 2.
data = self._read_status_file()
return int(_num_threads_re.findall(data)[0])
@wrap_exceptions
def threads(self):
thread_ids = os.listdir("%s/%s/task" % (self._procfs_path, self.pid))
thread_ids.sort()
retlist = []
hit_enoent = False
for thread_id in thread_ids:
fname = "%s/%s/task/%s/stat" % (
self._procfs_path, self.pid, thread_id)
try:
with open_binary(fname) as f:
st = f.read().strip()
except (FileNotFoundError, ProcessLookupError):
# no such file or directory or no such process;
# it means thread disappeared on us
hit_enoent = True
continue
# ignore the first two values ("pid (exe)")
st = st[st.find(b')') + 2:]
values = st.split(b' ')
utime = float(values[11]) / CLOCK_TICKS
stime = float(values[12]) / CLOCK_TICKS
ntuple = _common.pthread(int(thread_id), utime, stime)
retlist.append(ntuple)
if hit_enoent:
self._assert_alive()
return retlist
@wrap_exceptions
def nice_get(self):
# with open_text('%s/%s/stat' % (self._procfs_path, self.pid)) as f:
# data = f.read()
# return int(data.split()[18])
# Use C implementation
return cext_posix.getpriority(self.pid)
@wrap_exceptions
def nice_set(self, value):
return cext_posix.setpriority(self.pid, value)
# starting from CentOS 6.
if HAS_CPU_AFFINITY:
@wrap_exceptions
def cpu_affinity_get(self):
return cext.proc_cpu_affinity_get(self.pid)
def _get_eligible_cpus(
self, _re=re.compile(br"Cpus_allowed_list:\t(\d+)-(\d+)")):
# See: https://github.com/giampaolo/psutil/issues/956
data = self._read_status_file()
match = _re.findall(data)
if match:
return list(range(int(match[0][0]), int(match[0][1]) + 1))
else:
return list(range(len(per_cpu_times())))
@wrap_exceptions
def cpu_affinity_set(self, cpus):
try:
cext.proc_cpu_affinity_set(self.pid, cpus)
except (OSError, ValueError) as err:
if isinstance(err, ValueError) or err.errno == errno.EINVAL:
eligible_cpus = self._get_eligible_cpus()
all_cpus = tuple(range(len(per_cpu_times())))
for cpu in cpus:
if cpu not in all_cpus:
raise ValueError(
"invalid CPU number %r; choose between %s" % (
cpu, eligible_cpus))
if cpu not in eligible_cpus:
raise ValueError(
"CPU number %r is not eligible; choose "
"between %s" % (cpu, eligible_cpus))
raise
# only starting from kernel 2.6.13
if HAS_PROC_IO_PRIORITY:
@wrap_exceptions
def ionice_get(self):
ioclass, value = cext.proc_ioprio_get(self.pid)
if enum is not None:
ioclass = IOPriority(ioclass)
return _common.pionice(ioclass, value)
@wrap_exceptions
def ionice_set(self, ioclass, value):
if value is None:
value = 0
if value and ioclass in (IOPRIO_CLASS_IDLE, IOPRIO_CLASS_NONE):
raise ValueError("%r ioclass accepts no value" % ioclass)
if value < 0 or value > 7:
raise ValueError("value not in 0-7 range")
return cext.proc_ioprio_set(self.pid, ioclass, value)
if prlimit is not None:
@wrap_exceptions
def rlimit(self, resource_, limits=None):
# If pid is 0 prlimit() applies to the calling process and
# we don't want that. We should never get here though as
# PID 0 is not supported on Linux.
if self.pid == 0:
raise ValueError("can't use prlimit() against PID 0 process")
try:
if limits is None:
# get
return prlimit(self.pid, resource_)
else:
# set
if len(limits) != 2:
raise ValueError(
"second argument must be a (soft, hard) tuple, "
"got %s" % repr(limits))
prlimit(self.pid, resource_, limits)
except OSError as err:
if err.errno == errno.ENOSYS and pid_exists(self.pid):
# I saw this happening on Travis:
# https://travis-ci.org/giampaolo/psutil/jobs/51368273
raise ZombieProcess(self.pid, self._name, self._ppid)
else:
raise
@wrap_exceptions
def status(self):
letter = self._parse_stat_file()['status']
if PY3:
letter = letter.decode()
# XXX is '?' legit? (we're not supposed to return it anyway)
return PROC_STATUSES.get(letter, '?')
@wrap_exceptions
def open_files(self):
retlist = []
files = os.listdir("%s/%s/fd" % (self._procfs_path, self.pid))
hit_enoent = False
for fd in files:
file = "%s/%s/fd/%s" % (self._procfs_path, self.pid, fd)
try:
path = readlink(file)
except (FileNotFoundError, ProcessLookupError):
# ENOENT == file which is gone in the meantime
hit_enoent = True
continue
except OSError as err:
if err.errno == errno.EINVAL:
# not a link
continue
if err.errno == errno.ENAMETOOLONG:
# file name too long
debug(err)
continue
raise
else:
# If path is not an absolute there's no way to tell
# whether it's a regular file or not, so we skip it.
# A regular file is always supposed to be have an
# absolute path though.
if path.startswith('/') and isfile_strict(path):
# Get file position and flags.
file = "%s/%s/fdinfo/%s" % (
self._procfs_path, self.pid, fd)
try:
with open_binary(file) as f:
pos = int(f.readline().split()[1])
flags = int(f.readline().split()[1], 8)
except (FileNotFoundError, ProcessLookupError):
# fd gone in the meantime; process may
# still be alive
hit_enoent = True
else:
mode = file_flags_to_mode(flags)
ntuple = popenfile(
path, int(fd), int(pos), mode, flags)
retlist.append(ntuple)
if hit_enoent:
self._assert_alive()
return retlist
@wrap_exceptions
def connections(self, kind='inet'):
ret = _connections.retrieve(kind, self.pid)
self._assert_alive()
return ret
@wrap_exceptions
def num_fds(self):
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
@wrap_exceptions
def ppid(self):
return int(self._parse_stat_file()['ppid'])
@wrap_exceptions
def uids(self, _uids_re=re.compile(br'Uid:\t(\d+)\t(\d+)\t(\d+)')):
data = self._read_status_file()
real, effective, saved = _uids_re.findall(data)[0]
return _common.puids(int(real), int(effective), int(saved))
@wrap_exceptions
def gids(self, _gids_re=re.compile(br'Gid:\t(\d+)\t(\d+)\t(\d+)')):
data = self._read_status_file()
real, effective, saved = _gids_re.findall(data)[0]
return _common.pgids(int(real), int(effective), int(saved))
| 86,913 | 37.355693 | 88 | py |
psutil | psutil-master/psutil/_psosx.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""macOS platform implementation."""
import errno
import functools
import os
from collections import namedtuple
from . import _common
from . import _psposix
from . import _psutil_osx as cext
from . import _psutil_posix as cext_posix
from ._common import AccessDenied
from ._common import NoSuchProcess
from ._common import ZombieProcess
from ._common import conn_tmap
from ._common import conn_to_ntuple
from ._common import isfile_strict
from ._common import memoize_when_activated
from ._common import parse_environ_block
from ._common import usage_percent
from ._compat import PermissionError
from ._compat import ProcessLookupError
__extra__all__ = []
# =====================================================================
# --- globals
# =====================================================================
PAGESIZE = cext_posix.getpagesize()
AF_LINK = cext_posix.AF_LINK
TCP_STATUSES = {
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
cext.TCPS_CLOSED: _common.CONN_CLOSE,
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
cext.TCPS_LISTEN: _common.CONN_LISTEN,
cext.TCPS_CLOSING: _common.CONN_CLOSING,
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}
PROC_STATUSES = {
cext.SIDL: _common.STATUS_IDLE,
cext.SRUN: _common.STATUS_RUNNING,
cext.SSLEEP: _common.STATUS_SLEEPING,
cext.SSTOP: _common.STATUS_STOPPED,
cext.SZOMB: _common.STATUS_ZOMBIE,
}
kinfo_proc_map = dict(
ppid=0,
ruid=1,
euid=2,
suid=3,
rgid=4,
egid=5,
sgid=6,
ttynr=7,
ctime=8,
status=9,
name=10,
)
pidtaskinfo_map = dict(
cpuutime=0,
cpustime=1,
rss=2,
vms=3,
pfaults=4,
pageins=5,
numthreads=6,
volctxsw=7,
)
# =====================================================================
# --- named tuples
# =====================================================================
# psutil.cpu_times()
scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle'])
# psutil.virtual_memory()
svmem = namedtuple(
'svmem', ['total', 'available', 'percent', 'used', 'free',
'active', 'inactive', 'wired'])
# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms', 'pfaults', 'pageins'])
# psutil.Process.memory_full_info()
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
# =====================================================================
# --- memory
# =====================================================================
def virtual_memory():
"""System virtual memory as a namedtuple."""
total, active, inactive, wired, free, speculative = cext.virtual_mem()
# This is how Zabbix calculate avail and used mem:
# https://github.com/zabbix/zabbix/blob/trunk/src/libs/zbxsysinfo/
# osx/memory.c
# Also see: https://github.com/giampaolo/psutil/issues/1277
avail = inactive + free
used = active + wired
# This is NOT how Zabbix calculates free mem but it matches "free"
# cmdline utility.
free -= speculative
percent = usage_percent((total - avail), total, round_=1)
return svmem(total, avail, percent, used, free,
active, inactive, wired)
def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
total, used, free, sin, sout = cext.swap_mem()
percent = usage_percent(used, total, round_=1)
return _common.sswap(total, used, free, percent, sin, sout)
# =====================================================================
# --- CPU
# =====================================================================
def cpu_times():
"""Return system CPU times as a namedtuple."""
user, nice, system, idle = cext.cpu_times()
return scputimes(user, nice, system, idle)
def per_cpu_times():
"""Return system CPU times as a named tuple"""
ret = []
for cpu_t in cext.per_cpu_times():
user, nice, system, idle = cpu_t
item = scputimes(user, nice, system, idle)
ret.append(item)
return ret
def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
return cext.cpu_count_logical()
def cpu_count_cores():
"""Return the number of CPU cores in the system."""
return cext.cpu_count_cores()
def cpu_stats():
ctx_switches, interrupts, soft_interrupts, syscalls, traps = \
cext.cpu_stats()
return _common.scpustats(
ctx_switches, interrupts, soft_interrupts, syscalls)
def cpu_freq():
"""Return CPU frequency.
On macOS per-cpu frequency is not supported.
Also, the returned frequency never changes, see:
https://arstechnica.com/civis/viewtopic.php?f=19&t=465002
"""
curr, min_, max_ = cext.cpu_freq()
return [_common.scpufreq(curr, min_, max_)]
# =====================================================================
# --- disks
# =====================================================================
disk_usage = _psposix.disk_usage
disk_io_counters = cext.disk_io_counters
def disk_partitions(all=False):
"""Return mounted disk partitions as a list of namedtuples."""
retlist = []
partitions = cext.disk_partitions()
for partition in partitions:
device, mountpoint, fstype, opts = partition
if device == 'none':
device = ''
if not all:
if not os.path.isabs(device) or not os.path.exists(device):
continue
maxfile = maxpath = None # set later
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts,
maxfile, maxpath)
retlist.append(ntuple)
return retlist
# =====================================================================
# --- sensors
# =====================================================================
def sensors_battery():
"""Return battery information."""
try:
percent, minsleft, power_plugged = cext.sensors_battery()
except NotImplementedError:
# no power source - return None according to interface
return None
power_plugged = power_plugged == 1
if power_plugged:
secsleft = _common.POWER_TIME_UNLIMITED
elif minsleft == -1:
secsleft = _common.POWER_TIME_UNKNOWN
else:
secsleft = minsleft * 60
return _common.sbattery(percent, secsleft, power_plugged)
# =====================================================================
# --- network
# =====================================================================
net_io_counters = cext.net_io_counters
net_if_addrs = cext_posix.net_if_addrs
def net_connections(kind='inet'):
"""System-wide network connections."""
# Note: on macOS this will fail with AccessDenied unless
# the process is owned by root.
ret = []
for pid in pids():
try:
cons = Process(pid).connections(kind)
except NoSuchProcess:
continue
else:
if cons:
for c in cons:
c = list(c) + [pid]
ret.append(_common.sconn(*c))
return ret
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
names = net_io_counters().keys()
ret = {}
for name in names:
try:
mtu = cext_posix.net_if_mtu(name)
flags = cext_posix.net_if_flags(name)
duplex, speed = cext_posix.net_if_duplex_speed(name)
except OSError as err:
# https://github.com/giampaolo/psutil/issues/1279
if err.errno != errno.ENODEV:
raise
else:
if hasattr(_common, 'NicDuplex'):
duplex = _common.NicDuplex(duplex)
output_flags = ','.join(flags)
isup = 'running' in flags
ret[name] = _common.snicstats(isup, duplex, speed, mtu,
output_flags)
return ret
# =====================================================================
# --- other system functions
# =====================================================================
def boot_time():
"""The system boot time expressed in seconds since the epoch."""
return cext.boot_time()
def users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = cext.users()
for item in rawlist:
user, tty, hostname, tstamp, pid = item
if tty == '~':
continue # reboot or shutdown
if not tstamp:
continue
nt = _common.suser(user, tty or None, hostname or None, tstamp, pid)
retlist.append(nt)
return retlist
# =====================================================================
# --- processes
# =====================================================================
def pids():
ls = cext.pids()
if 0 not in ls:
# On certain macOS versions pids() C doesn't return PID 0 but
# "ps" does and the process is querable via sysctl():
# https://travis-ci.org/giampaolo/psutil/jobs/309619941
try:
Process(0).create_time()
ls.insert(0, 0)
except NoSuchProcess:
pass
except AccessDenied:
ls.insert(0, 0)
return ls
pid_exists = _psposix.pid_exists
def is_zombie(pid):
try:
st = cext.proc_kinfo_oneshot(pid)[kinfo_proc_map['status']]
return st == cext.SZOMB
except Exception:
return False
def wrap_exceptions(fun):
"""Decorator which translates bare OSError exceptions into
NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except ProcessLookupError:
if is_zombie(self.pid):
raise ZombieProcess(self.pid, self._name, self._ppid)
else:
raise NoSuchProcess(self.pid, self._name)
except PermissionError:
raise AccessDenied(self.pid, self._name)
return wrapper
class Process(object):
"""Wrapper class around underlying C implementation."""
__slots__ = ["pid", "_name", "_ppid", "_cache"]
def __init__(self, pid):
self.pid = pid
self._name = None
self._ppid = None
@wrap_exceptions
@memoize_when_activated
def _get_kinfo_proc(self):
# Note: should work with all PIDs without permission issues.
ret = cext.proc_kinfo_oneshot(self.pid)
assert len(ret) == len(kinfo_proc_map)
return ret
@wrap_exceptions
@memoize_when_activated
def _get_pidtaskinfo(self):
# Note: should work for PIDs owned by user only.
ret = cext.proc_pidtaskinfo_oneshot(self.pid)
assert len(ret) == len(pidtaskinfo_map)
return ret
def oneshot_enter(self):
self._get_kinfo_proc.cache_activate(self)
self._get_pidtaskinfo.cache_activate(self)
def oneshot_exit(self):
self._get_kinfo_proc.cache_deactivate(self)
self._get_pidtaskinfo.cache_deactivate(self)
@wrap_exceptions
def name(self):
name = self._get_kinfo_proc()[kinfo_proc_map['name']]
return name if name is not None else cext.proc_name(self.pid)
@wrap_exceptions
def exe(self):
return cext.proc_exe(self.pid)
@wrap_exceptions
def cmdline(self):
return cext.proc_cmdline(self.pid)
@wrap_exceptions
def environ(self):
return parse_environ_block(cext.proc_environ(self.pid))
@wrap_exceptions
def ppid(self):
self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']]
return self._ppid
@wrap_exceptions
def cwd(self):
return cext.proc_cwd(self.pid)
@wrap_exceptions
def uids(self):
rawtuple = self._get_kinfo_proc()
return _common.puids(
rawtuple[kinfo_proc_map['ruid']],
rawtuple[kinfo_proc_map['euid']],
rawtuple[kinfo_proc_map['suid']])
@wrap_exceptions
def gids(self):
rawtuple = self._get_kinfo_proc()
return _common.puids(
rawtuple[kinfo_proc_map['rgid']],
rawtuple[kinfo_proc_map['egid']],
rawtuple[kinfo_proc_map['sgid']])
@wrap_exceptions
def terminal(self):
tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']]
tmap = _psposix.get_terminal_map()
try:
return tmap[tty_nr]
except KeyError:
return None
@wrap_exceptions
def memory_info(self):
rawtuple = self._get_pidtaskinfo()
return pmem(
rawtuple[pidtaskinfo_map['rss']],
rawtuple[pidtaskinfo_map['vms']],
rawtuple[pidtaskinfo_map['pfaults']],
rawtuple[pidtaskinfo_map['pageins']],
)
@wrap_exceptions
def memory_full_info(self):
basic_mem = self.memory_info()
uss = cext.proc_memory_uss(self.pid)
return pfullmem(*basic_mem + (uss, ))
@wrap_exceptions
def cpu_times(self):
rawtuple = self._get_pidtaskinfo()
return _common.pcputimes(
rawtuple[pidtaskinfo_map['cpuutime']],
rawtuple[pidtaskinfo_map['cpustime']],
# children user / system times are not retrievable (set to 0)
0.0, 0.0)
@wrap_exceptions
def create_time(self):
return self._get_kinfo_proc()[kinfo_proc_map['ctime']]
@wrap_exceptions
def num_ctx_switches(self):
# Unvoluntary value seems not to be available;
# getrusage() numbers seems to confirm this theory.
# We set it to 0.
vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']]
return _common.pctxsw(vol, 0)
@wrap_exceptions
def num_threads(self):
return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']]
@wrap_exceptions
def open_files(self):
if self.pid == 0:
return []
files = []
rawlist = cext.proc_open_files(self.pid)
for path, fd in rawlist:
if isfile_strict(path):
ntuple = _common.popenfile(path, fd)
files.append(ntuple)
return files
@wrap_exceptions
def connections(self, kind='inet'):
if kind not in conn_tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in conn_tmap])))
families, types = conn_tmap[kind]
rawlist = cext.proc_connections(self.pid, families, types)
ret = []
for item in rawlist:
fd, fam, type, laddr, raddr, status = item
nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status,
TCP_STATUSES)
ret.append(nt)
return ret
@wrap_exceptions
def num_fds(self):
if self.pid == 0:
return 0
return cext.proc_num_fds(self.pid)
@wrap_exceptions
def wait(self, timeout=None):
return _psposix.wait_pid(self.pid, timeout, self._name)
@wrap_exceptions
def nice_get(self):
return cext_posix.getpriority(self.pid)
@wrap_exceptions
def nice_set(self, value):
return cext_posix.setpriority(self.pid, value)
@wrap_exceptions
def status(self):
code = self._get_kinfo_proc()[kinfo_proc_map['status']]
# XXX is '?' legit? (we're not supposed to return it anyway)
return PROC_STATUSES.get(code, '?')
@wrap_exceptions
def threads(self):
rawlist = cext.proc_threads(self.pid)
retlist = []
for thread_id, utime, stime in rawlist:
ntuple = _common.pthread(thread_id, utime, stime)
retlist.append(ntuple)
return retlist
| 16,169 | 28.833948 | 79 | py |
psutil | psutil-master/psutil/_psposix.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Routines common to all posix systems."""
import glob
import os
import signal
import sys
import time
from ._common import MACOS
from ._common import TimeoutExpired
from ._common import memoize
from ._common import sdiskusage
from ._common import usage_percent
from ._compat import PY3
from ._compat import ChildProcessError
from ._compat import FileNotFoundError
from ._compat import InterruptedError
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import unicode
if MACOS:
from . import _psutil_osx
if sys.version_info >= (3, 4):
import enum
else:
enum = None
__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map']
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid == 0:
# According to "man 2 kill" PID 0 has a special meaning:
# it refers to <<every process in the process group of the
# calling process>> so we don't want to go any further.
# If we get here it means this UNIX platform *does* have
# a process with id 0.
return True
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
# EPERM clearly means there's a process to deny access to
return True
# According to "man 2 kill" possible error values are
# (EINVAL, EPERM, ESRCH)
else:
return True
# Python 3.5 signals enum (contributed by me ^^):
# https://bugs.python.org/issue21076
if enum is not None and hasattr(signal, "Signals"):
Negsignal = enum.IntEnum(
'Negsignal', dict([(x.name, -x.value) for x in signal.Signals]))
def negsig_to_enum(num):
"""Convert a negative signal value to an enum."""
try:
return Negsignal(num)
except ValueError:
return num
else: # pragma: no cover
def negsig_to_enum(num):
return num
def wait_pid(pid, timeout=None, proc_name=None,
_waitpid=os.waitpid,
_timer=getattr(time, 'monotonic', time.time),
_min=min,
_sleep=time.sleep,
_pid_exists=pid_exists):
"""Wait for a process PID to terminate.
If the process terminated normally by calling exit(3) or _exit(2),
or by returning from main(), the return value is the positive integer
passed to *exit().
If it was terminated by a signal it returns the negated value of the
signal which caused the termination (e.g. -SIGTERM).
If PID is not a children of os.getpid() (current process) just
wait until the process disappears and return None.
If PID does not exist at all return None immediately.
If *timeout* != None and process is still alive raise TimeoutExpired.
timeout=0 is also possible (either return immediately or raise).
"""
if pid <= 0:
raise ValueError("can't wait for PID 0") # see "man waitpid"
interval = 0.0001
flags = 0
if timeout is not None:
flags |= os.WNOHANG
stop_at = _timer() + timeout
def sleep(interval):
# Sleep for some time and return a new increased interval.
if timeout is not None:
if _timer() >= stop_at:
raise TimeoutExpired(timeout, pid=pid, name=proc_name)
_sleep(interval)
return _min(interval * 2, 0.04)
# See: https://linux.die.net/man/2/waitpid
while True:
try:
retpid, status = os.waitpid(pid, flags)
except InterruptedError:
interval = sleep(interval)
except ChildProcessError:
# This has two meanings:
# - PID is not a child of os.getpid() in which case
# we keep polling until it's gone
# - PID never existed in the first place
# In both cases we'll eventually return None as we
# can't determine its exit status code.
while _pid_exists(pid):
interval = sleep(interval)
return
else:
if retpid == 0:
# WNOHANG flag was used and PID is still running.
interval = sleep(interval)
continue
elif os.WIFEXITED(status):
# Process terminated normally by calling exit(3) or _exit(2),
# or by returning from main(). The return value is the
# positive integer passed to *exit().
return os.WEXITSTATUS(status)
elif os.WIFSIGNALED(status):
# Process exited due to a signal. Return the negative value
# of that signal.
return negsig_to_enum(-os.WTERMSIG(status))
# elif os.WIFSTOPPED(status):
# # Process was stopped via SIGSTOP or is being traced, and
# # waitpid() was called with WUNTRACED flag. PID is still
# # alive. From now on waitpid() will keep returning (0, 0)
# # until the process state doesn't change.
# # It may make sense to catch/enable this since stopped PIDs
# # ignore SIGTERM.
# interval = sleep(interval)
# continue
# elif os.WIFCONTINUED(status):
# # Process was resumed via SIGCONT and waitpid() was called
# # with WCONTINUED flag.
# interval = sleep(interval)
# continue
else:
# Should never happen.
raise ValueError("unknown process exit status %r" % status)
def disk_usage(path):
"""Return disk usage associated with path.
Note: UNIX usually reserves 5% disk space which is not accessible
by user. In this function "total" and "used" values reflect the
total and used disk space whereas "free" and "percent" represent
the "free" and "used percent" user disk space.
"""
if PY3:
st = os.statvfs(path)
else: # pragma: no cover
# os.statvfs() does not support unicode on Python 2:
# - https://github.com/giampaolo/psutil/issues/416
# - http://bugs.python.org/issue18695
try:
st = os.statvfs(path)
except UnicodeEncodeError:
if isinstance(path, unicode):
try:
path = path.encode(sys.getfilesystemencoding())
except UnicodeEncodeError:
pass
st = os.statvfs(path)
else:
raise
# Total space which is only available to root (unless changed
# at system level).
total = (st.f_blocks * st.f_frsize)
# Remaining free space usable by root.
avail_to_root = (st.f_bfree * st.f_frsize)
# Remaining free space usable by user.
avail_to_user = (st.f_bavail * st.f_frsize)
# Total space being used in general.
used = (total - avail_to_root)
if MACOS:
# see: https://github.com/giampaolo/psutil/pull/2152
used = _psutil_osx.disk_usage_used(path, used)
# Total space which is available to user (same as 'total' but
# for the user).
total_user = used + avail_to_user
# User usage percent compared to the total amount of space
# the user can use. This number would be higher if compared
# to root's because the user has less space (usually -5%).
usage_percent_user = usage_percent(used, total_user, round_=1)
# NB: the percentage is -5% than what shown by df due to
# reserved blocks that we are currently not considering:
# https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462
return sdiskusage(
total=total, used=used, free=avail_to_user, percent=usage_percent_user)
@memoize
def get_terminal_map():
"""Get a map of device-id -> path as a dict.
Used by Process.terminal()
"""
ret = {}
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
for name in ls:
assert name not in ret, name
try:
ret[os.stat(name).st_rdev] = name
except FileNotFoundError:
pass
return ret
| 8,245 | 34.390558 | 79 | py |
psutil | psutil-master/psutil/_pssunos.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Sun OS Solaris platform implementation."""
import errno
import functools
import os
import socket
import subprocess
import sys
from collections import namedtuple
from socket import AF_INET
from . import _common
from . import _psposix
from . import _psutil_posix as cext_posix
from . import _psutil_sunos as cext
from ._common import AF_INET6
from ._common import AccessDenied
from ._common import NoSuchProcess
from ._common import ZombieProcess
from ._common import debug
from ._common import get_procfs_path
from ._common import isfile_strict
from ._common import memoize_when_activated
from ._common import sockfam_to_enum
from ._common import socktype_to_enum
from ._common import usage_percent
from ._compat import PY3
from ._compat import FileNotFoundError
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import b
__extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"]
# =====================================================================
# --- globals
# =====================================================================
PAGE_SIZE = cext_posix.getpagesize()
AF_LINK = cext_posix.AF_LINK
IS_64_BIT = sys.maxsize > 2**32
CONN_IDLE = "IDLE"
CONN_BOUND = "BOUND"
PROC_STATUSES = {
cext.SSLEEP: _common.STATUS_SLEEPING,
cext.SRUN: _common.STATUS_RUNNING,
cext.SZOMB: _common.STATUS_ZOMBIE,
cext.SSTOP: _common.STATUS_STOPPED,
cext.SIDL: _common.STATUS_IDLE,
cext.SONPROC: _common.STATUS_RUNNING, # same as run
cext.SWAIT: _common.STATUS_WAITING,
}
TCP_STATUSES = {
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
cext.TCPS_CLOSED: _common.CONN_CLOSE,
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
cext.TCPS_LISTEN: _common.CONN_LISTEN,
cext.TCPS_CLOSING: _common.CONN_CLOSING,
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
cext.TCPS_IDLE: CONN_IDLE, # sunos specific
cext.TCPS_BOUND: CONN_BOUND, # sunos specific
}
proc_info_map = dict(
ppid=0,
rss=1,
vms=2,
create_time=3,
nice=4,
num_threads=5,
status=6,
ttynr=7,
uid=8,
euid=9,
gid=10,
egid=11)
# =====================================================================
# --- named tuples
# =====================================================================
# psutil.cpu_times()
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
# psutil.cpu_times(percpu=True)
pcputimes = namedtuple('pcputimes',
['user', 'system', 'children_user', 'children_system'])
# psutil.virtual_memory()
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms'])
pfullmem = pmem
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple('pmmap_grouped',
['path', 'rss', 'anonymous', 'locked'])
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
# =====================================================================
# --- memory
# =====================================================================
def virtual_memory():
"""Report virtual memory metrics."""
# we could have done this with kstat, but IMHO this is good enough
total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
# note: there's no difference on Solaris
free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE
used = total - free
percent = usage_percent(used, total, round_=1)
return svmem(total, avail, percent, used, free)
def swap_memory():
"""Report swap memory metrics."""
sin, sout = cext.swap_mem()
# XXX
# we are supposed to get total/free by doing so:
# http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/
# usr/src/cmd/swap/swap.c
# ...nevertheless I can't manage to obtain the same numbers as 'swap'
# cmdline utility, so let's parse its output (sigh!)
p = subprocess.Popen(['/usr/bin/env', 'PATH=/usr/sbin:/sbin:%s' %
os.environ['PATH'], 'swap', '-l'],
stdout=subprocess.PIPE)
stdout, _ = p.communicate()
if PY3:
stdout = stdout.decode(sys.stdout.encoding)
if p.returncode != 0:
raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode)
lines = stdout.strip().split('\n')[1:]
if not lines:
raise RuntimeError('no swap device(s) configured')
total = free = 0
for line in lines:
line = line.split()
t, f = line[3:5]
total += int(int(t) * 512)
free += int(int(f) * 512)
used = total - free
percent = usage_percent(used, total, round_=1)
return _common.sswap(total, used, free, percent,
sin * PAGE_SIZE, sout * PAGE_SIZE)
# =====================================================================
# --- CPU
# =====================================================================
def cpu_times():
"""Return system-wide CPU times as a named tuple"""
ret = cext.per_cpu_times()
return scputimes(*[sum(x) for x in zip(*ret)])
def per_cpu_times():
"""Return system per-CPU times as a list of named tuples"""
ret = cext.per_cpu_times()
return [scputimes(*x) for x in ret]
def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
# mimic os.cpu_count() behavior
return None
def cpu_count_cores():
"""Return the number of CPU cores in the system."""
return cext.cpu_count_cores()
def cpu_stats():
"""Return various CPU stats as a named tuple."""
ctx_switches, interrupts, syscalls, traps = cext.cpu_stats()
soft_interrupts = 0
return _common.scpustats(ctx_switches, interrupts, soft_interrupts,
syscalls)
# =====================================================================
# --- disks
# =====================================================================
disk_io_counters = cext.disk_io_counters
disk_usage = _psposix.disk_usage
def disk_partitions(all=False):
"""Return system disk partitions."""
# TODO - the filtering logic should be better checked so that
# it tries to reflect 'df' as much as possible
retlist = []
partitions = cext.disk_partitions()
for partition in partitions:
device, mountpoint, fstype, opts = partition
if device == 'none':
device = ''
if not all:
# Differently from, say, Linux, we don't have a list of
# common fs types so the best we can do, AFAIK, is to
# filter by filesystem having a total size > 0.
try:
if not disk_usage(mountpoint).total:
continue
except OSError as err:
# https://github.com/giampaolo/psutil/issues/1674
debug("skipping %r: %s" % (mountpoint, err))
continue
maxfile = maxpath = None # set later
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts,
maxfile, maxpath)
retlist.append(ntuple)
return retlist
# =====================================================================
# --- network
# =====================================================================
net_io_counters = cext.net_io_counters
net_if_addrs = cext_posix.net_if_addrs
def net_connections(kind, _pid=-1):
"""Return socket connections. If pid == -1 return system-wide
connections (as opposed to connections opened by one process only).
Only INET sockets are returned (UNIX are not).
"""
cmap = _common.conn_tmap.copy()
if _pid == -1:
cmap.pop('unix', 0)
if kind not in cmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in cmap])))
families, types = _common.conn_tmap[kind]
rawlist = cext.net_connections(_pid)
ret = set()
for item in rawlist:
fd, fam, type_, laddr, raddr, status, pid = item
if fam not in families:
continue
if type_ not in types:
continue
# TODO: refactor and use _common.conn_to_ntuple.
if fam in (AF_INET, AF_INET6):
if laddr:
laddr = _common.addr(*laddr)
if raddr:
raddr = _common.addr(*raddr)
status = TCP_STATUSES[status]
fam = sockfam_to_enum(fam)
type_ = socktype_to_enum(type_)
if _pid == -1:
nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid)
else:
nt = _common.pconn(fd, fam, type_, laddr, raddr, status)
ret.add(nt)
return list(ret)
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
ret = cext.net_if_stats()
for name, items in ret.items():
isup, duplex, speed, mtu = items
if hasattr(_common, 'NicDuplex'):
duplex = _common.NicDuplex(duplex)
ret[name] = _common.snicstats(isup, duplex, speed, mtu, '')
return ret
# =====================================================================
# --- other system functions
# =====================================================================
def boot_time():
"""The system boot time expressed in seconds since the epoch."""
return cext.boot_time()
def users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = cext.users()
localhost = (':0.0', ':0')
for item in rawlist:
user, tty, hostname, tstamp, user_process, pid = item
# note: the underlying C function includes entries about
# system boot, run level and others. We might want
# to use them in the future.
if not user_process:
continue
if hostname in localhost:
hostname = 'localhost'
nt = _common.suser(user, tty, hostname, tstamp, pid)
retlist.append(nt)
return retlist
# =====================================================================
# --- processes
# =====================================================================
def pids():
"""Returns a list of PIDs currently running on the system."""
return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
def pid_exists(pid):
"""Check for the existence of a unix pid."""
return _psposix.pid_exists(pid)
def wrap_exceptions(fun):
"""Call callable into a try/except clause and translate ENOENT,
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except (FileNotFoundError, ProcessLookupError):
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
except PermissionError:
raise AccessDenied(self.pid, self._name)
except OSError:
if self.pid == 0:
if 0 in pids():
raise AccessDenied(self.pid, self._name)
else:
raise
raise
return wrapper
class Process(object):
"""Wrapper class around underlying C implementation."""
__slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
def __init__(self, pid):
self.pid = pid
self._name = None
self._ppid = None
self._procfs_path = get_procfs_path()
def _assert_alive(self):
"""Raise NSP if the process disappeared on us."""
# For those C function who do not raise NSP, possibly returning
# incorrect or incomplete result.
os.stat('%s/%s' % (self._procfs_path, self.pid))
def oneshot_enter(self):
self._proc_name_and_args.cache_activate(self)
self._proc_basic_info.cache_activate(self)
self._proc_cred.cache_activate(self)
def oneshot_exit(self):
self._proc_name_and_args.cache_deactivate(self)
self._proc_basic_info.cache_deactivate(self)
self._proc_cred.cache_deactivate(self)
@wrap_exceptions
@memoize_when_activated
def _proc_name_and_args(self):
return cext.proc_name_and_args(self.pid, self._procfs_path)
@wrap_exceptions
@memoize_when_activated
def _proc_basic_info(self):
if self.pid == 0 and not \
os.path.exists('%s/%s/psinfo' % (self._procfs_path, self.pid)):
raise AccessDenied(self.pid)
ret = cext.proc_basic_info(self.pid, self._procfs_path)
assert len(ret) == len(proc_info_map)
return ret
@wrap_exceptions
@memoize_when_activated
def _proc_cred(self):
return cext.proc_cred(self.pid, self._procfs_path)
@wrap_exceptions
def name(self):
# note: max len == 15
return self._proc_name_and_args()[0]
@wrap_exceptions
def exe(self):
try:
return os.readlink(
"%s/%s/path/a.out" % (self._procfs_path, self.pid))
except OSError:
pass # continue and guess the exe name from the cmdline
# Will be guessed later from cmdline but we want to explicitly
# invoke cmdline here in order to get an AccessDenied
# exception if the user has not enough privileges.
self.cmdline()
return ""
@wrap_exceptions
def cmdline(self):
return self._proc_name_and_args()[1].split(' ')
@wrap_exceptions
def environ(self):
return cext.proc_environ(self.pid, self._procfs_path)
@wrap_exceptions
def create_time(self):
return self._proc_basic_info()[proc_info_map['create_time']]
@wrap_exceptions
def num_threads(self):
return self._proc_basic_info()[proc_info_map['num_threads']]
@wrap_exceptions
def nice_get(self):
# Note #1: getpriority(3) doesn't work for realtime processes.
# Psinfo is what ps uses, see:
# https://github.com/giampaolo/psutil/issues/1194
return self._proc_basic_info()[proc_info_map['nice']]
@wrap_exceptions
def nice_set(self, value):
if self.pid in (2, 3):
# Special case PIDs: internally setpriority(3) return ESRCH
# (no such process), no matter what.
# The process actually exists though, as it has a name,
# creation time, etc.
raise AccessDenied(self.pid, self._name)
return cext_posix.setpriority(self.pid, value)
@wrap_exceptions
def ppid(self):
self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
return self._ppid
@wrap_exceptions
def uids(self):
try:
real, effective, saved, _, _, _ = self._proc_cred()
except AccessDenied:
real = self._proc_basic_info()[proc_info_map['uid']]
effective = self._proc_basic_info()[proc_info_map['euid']]
saved = None
return _common.puids(real, effective, saved)
@wrap_exceptions
def gids(self):
try:
_, _, _, real, effective, saved = self._proc_cred()
except AccessDenied:
real = self._proc_basic_info()[proc_info_map['gid']]
effective = self._proc_basic_info()[proc_info_map['egid']]
saved = None
return _common.puids(real, effective, saved)
@wrap_exceptions
def cpu_times(self):
try:
times = cext.proc_cpu_times(self.pid, self._procfs_path)
except OSError as err:
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
# We may get here if we attempt to query a 64bit process
# with a 32bit python.
# Error originates from read() and also tools like "cat"
# fail in the same way (!).
# Since there simply is no way to determine CPU times we
# return 0.0 as a fallback. See:
# https://github.com/giampaolo/psutil/issues/857
times = (0.0, 0.0, 0.0, 0.0)
else:
raise
return _common.pcputimes(*times)
@wrap_exceptions
def cpu_num(self):
return cext.proc_cpu_num(self.pid, self._procfs_path)
@wrap_exceptions
def terminal(self):
procfs_path = self._procfs_path
hit_enoent = False
tty = wrap_exceptions(
self._proc_basic_info()[proc_info_map['ttynr']])
if tty != cext.PRNODEV:
for x in (0, 1, 2, 255):
try:
return os.readlink(
'%s/%d/path/%d' % (procfs_path, self.pid, x))
except FileNotFoundError:
hit_enoent = True
continue
if hit_enoent:
self._assert_alive()
@wrap_exceptions
def cwd(self):
# /proc/PID/path/cwd may not be resolved by readlink() even if
# it exists (ls shows it). If that's the case and the process
# is still alive return None (we can return None also on BSD).
# Reference: http://goo.gl/55XgO
procfs_path = self._procfs_path
try:
return os.readlink("%s/%s/path/cwd" % (procfs_path, self.pid))
except FileNotFoundError:
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
return ""
@wrap_exceptions
def memory_info(self):
ret = self._proc_basic_info()
rss = ret[proc_info_map['rss']] * 1024
vms = ret[proc_info_map['vms']] * 1024
return pmem(rss, vms)
memory_full_info = memory_info
@wrap_exceptions
def status(self):
code = self._proc_basic_info()[proc_info_map['status']]
# XXX is '?' legit? (we're not supposed to return it anyway)
return PROC_STATUSES.get(code, '?')
@wrap_exceptions
def threads(self):
procfs_path = self._procfs_path
ret = []
tids = os.listdir('%s/%d/lwp' % (procfs_path, self.pid))
hit_enoent = False
for tid in tids:
tid = int(tid)
try:
utime, stime = cext.query_process_thread(
self.pid, tid, procfs_path)
except EnvironmentError as err:
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
# We may get here if we attempt to query a 64bit process
# with a 32bit python.
# Error originates from read() and also tools like "cat"
# fail in the same way (!).
# Since there simply is no way to determine CPU times we
# return 0.0 as a fallback. See:
# https://github.com/giampaolo/psutil/issues/857
continue
# ENOENT == thread gone in meantime
if err.errno == errno.ENOENT:
hit_enoent = True
continue
raise
else:
nt = _common.pthread(tid, utime, stime)
ret.append(nt)
if hit_enoent:
self._assert_alive()
return ret
@wrap_exceptions
def open_files(self):
retlist = []
hit_enoent = False
procfs_path = self._procfs_path
pathdir = '%s/%d/path' % (procfs_path, self.pid)
for fd in os.listdir('%s/%d/fd' % (procfs_path, self.pid)):
path = os.path.join(pathdir, fd)
if os.path.islink(path):
try:
file = os.readlink(path)
except FileNotFoundError:
hit_enoent = True
continue
else:
if isfile_strict(file):
retlist.append(_common.popenfile(file, int(fd)))
if hit_enoent:
self._assert_alive()
return retlist
def _get_unix_sockets(self, pid):
"""Get UNIX sockets used by process by parsing 'pfiles' output."""
# TODO: rewrite this in C (...but the damn netstat source code
# does not include this part! Argh!!)
cmd = "pfiles %s" % pid
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if PY3:
stdout, stderr = [x.decode(sys.stdout.encoding)
for x in (stdout, stderr)]
if p.returncode != 0:
if 'permission denied' in stderr.lower():
raise AccessDenied(self.pid, self._name)
if 'no such process' in stderr.lower():
raise NoSuchProcess(self.pid, self._name)
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
lines = stdout.split('\n')[2:]
for i, line in enumerate(lines):
line = line.lstrip()
if line.startswith('sockname: AF_UNIX'):
path = line.split(' ', 2)[2]
type = lines[i - 2].strip()
if type == 'SOCK_STREAM':
type = socket.SOCK_STREAM
elif type == 'SOCK_DGRAM':
type = socket.SOCK_DGRAM
else:
type = -1
yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
@wrap_exceptions
def connections(self, kind='inet'):
ret = net_connections(kind, _pid=self.pid)
# The underlying C implementation retrieves all OS connections
# and filters them by PID. At this point we can't tell whether
# an empty list means there were no connections for process or
# process is no longer active so we force NSP in case the PID
# is no longer there.
if not ret:
# will raise NSP if process is gone
os.stat('%s/%s' % (self._procfs_path, self.pid))
# UNIX sockets
if kind in ('all', 'unix'):
ret.extend([_common.pconn(*conn) for conn in
self._get_unix_sockets(self.pid)])
return ret
nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked')
nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked')
@wrap_exceptions
def memory_maps(self):
def toaddr(start, end):
return '%s-%s' % (hex(start)[2:].strip('L'),
hex(end)[2:].strip('L'))
procfs_path = self._procfs_path
retlist = []
try:
rawlist = cext.proc_memory_maps(self.pid, procfs_path)
except OSError as err:
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
# We may get here if we attempt to query a 64bit process
# with a 32bit python.
# Error originates from read() and also tools like "cat"
# fail in the same way (!).
# Since there simply is no way to determine CPU times we
# return 0.0 as a fallback. See:
# https://github.com/giampaolo/psutil/issues/857
return []
else:
raise
hit_enoent = False
for item in rawlist:
addr, addrsize, perm, name, rss, anon, locked = item
addr = toaddr(addr, addrsize)
if not name.startswith('['):
try:
name = os.readlink(
'%s/%s/path/%s' % (procfs_path, self.pid, name))
except OSError as err:
if err.errno == errno.ENOENT:
# sometimes the link may not be resolved by
# readlink() even if it exists (ls shows it).
# If that's the case we just return the
# unresolved link path.
# This seems an incosistency with /proc similar
# to: http://goo.gl/55XgO
name = '%s/%s/path/%s' % (procfs_path, self.pid, name)
hit_enoent = True
else:
raise
retlist.append((addr, perm, name, rss, anon, locked))
if hit_enoent:
self._assert_alive()
return retlist
@wrap_exceptions
def num_fds(self):
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
@wrap_exceptions
def num_ctx_switches(self):
return _common.pctxsw(
*cext.proc_num_ctx_switches(self.pid, self._procfs_path))
@wrap_exceptions
def wait(self, timeout=None):
return _psposix.wait_pid(self.pid, timeout, self._name)
| 25,486 | 34.009615 | 79 | py |
psutil | psutil-master/psutil/_psutil_aix.c | /*
* Copyright (c) 2009, Giampaolo Rodola'
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
* AIX support is experimental at this time.
* The following functions and methods are unsupported on the AIX platform:
* - psutil.Process.memory_maps
*
* Known limitations:
* - psutil.Process.io_counters read count is always 0
* - psutil.Process.io_counters may not be available on older AIX versions
* - psutil.Process.threads may not be available on older AIX versions
* - psutil.net_io_counters may not be available on older AIX versions
* - reading basic process info may fail or return incorrect values when
* process is starting (see IBM APAR IV58499 - fixed in newer AIX versions)
* - sockets and pipes may not be counted in num_fds (fixed in newer AIX
* versions)
*
* Useful resources:
* - proc filesystem: http://www-01.ibm.com/support/knowledgecenter/
* ssw_aix_72/com.ibm.aix.files/proc.htm
* - libperfstat: http://www-01.ibm.com/support/knowledgecenter/
* ssw_aix_72/com.ibm.aix.files/libperfstat.h.htm
*/
#include <Python.h>
#include <sys/limits.h>
#include <sys/proc.h>
#include <sys/procfs.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <sys/thread.h>
#include <sys/types.h>
#include <fcntl.h>
#include <utmp.h>
#include <utmpx.h>
#include <mntent.h>
#include <sys/ioctl.h>
#include <sys/tihdr.h>
#include <stropts.h>
#include <netinet/tcp_fsm.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <libperfstat.h>
#include <unistd.h>
#include "_psutil_common.h"
#include "_psutil_posix.h"
#include "arch/aix/ifaddrs.h"
#include "arch/aix/net_connections.h"
#include "arch/aix/common.h"
#define TV2DOUBLE(t) (((t).tv_nsec * 0.000000001) + (t).tv_sec)
/*
* Read a file content and fills a C structure with it.
*/
int
psutil_file_to_struct(char *path, void *fstruct, size_t size) {
int fd;
size_t nbytes;
fd = open(path, O_RDONLY);
if (fd == -1) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
return 0;
}
nbytes = read(fd, fstruct, size);
if (nbytes <= 0) {
close(fd);
PyErr_SetFromErrno(PyExc_OSError);
return 0;
}
if (nbytes != size) {
close(fd);
PyErr_SetString(PyExc_RuntimeError, "structure size mismatch");
return 0;
}
close(fd);
return nbytes;
}
/*
* Return process ppid, rss, vms, ctime, nice, nthreads, status and tty
* as a Python tuple.
*/
static PyObject *
psutil_proc_basic_info(PyObject *self, PyObject *args) {
int pid;
char path[100];
psinfo_t info;
pstatus_t status;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/psinfo", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
if (info.pr_nlwp == 0 && info.pr_lwp.pr_lwpid == 0) {
// From the /proc docs: "If the process is a zombie, the pr_nlwp
// and pr_lwp.pr_lwpid flags are zero."
status.pr_stat = SZOMB;
} else if (info.pr_flag & SEXIT) {
// "exiting" processes don't have /proc/<pid>/status
// There are other "exiting" processes that 'ps' shows as "active"
status.pr_stat = SACTIVE;
} else {
sprintf(path, "%s/%i/status", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&status, sizeof(status)))
return NULL;
}
return Py_BuildValue("KKKdiiiK",
(unsigned long long) info.pr_ppid, // parent pid
(unsigned long long) info.pr_rssize, // rss
(unsigned long long) info.pr_size, // vms
TV2DOUBLE(info.pr_start), // create time
(int) info.pr_lwp.pr_nice, // nice
(int) info.pr_nlwp, // no. of threads
(int) status.pr_stat, // status code
(unsigned long long)info.pr_ttydev // tty nr
);
}
/*
* Return process name as a Python string.
*/
static PyObject *
psutil_proc_name(PyObject *self, PyObject *args) {
int pid;
char path[100];
psinfo_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/psinfo", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
return PyUnicode_DecodeFSDefaultAndSize(info.pr_fname, PRFNSZ);
}
/*
* Return process command line arguments as a Python list
*/
static PyObject *
psutil_proc_args(PyObject *self, PyObject *args) {
int pid;
PyObject *py_retlist = PyList_New(0);
PyObject *py_arg = NULL;
struct procsinfo procbuf;
long arg_max;
char *argbuf = NULL;
char *curarg = NULL;
int ret;
if (py_retlist == NULL)
return NULL;
if (!PyArg_ParseTuple(args, "i", &pid))
goto error;
arg_max = sysconf(_SC_ARG_MAX);
argbuf = malloc(arg_max);
if (argbuf == NULL) {
PyErr_NoMemory();
goto error;
}
procbuf.pi_pid = pid;
ret = getargs(&procbuf, sizeof(procbuf), argbuf, ARG_MAX);
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
curarg = argbuf;
/* getargs will always append an extra NULL to end the arg list,
* even if the buffer is not big enough (even though it is supposed
* to be) so the following 'while' is safe */
while (*curarg != '\0') {
py_arg = PyUnicode_DecodeFSDefault(curarg);
if (!py_arg)
goto error;
if (PyList_Append(py_retlist, py_arg))
goto error;
Py_DECREF(py_arg);
curarg = strchr(curarg, '\0') + 1;
}
free(argbuf);
return py_retlist;
error:
if (argbuf != NULL)
free(argbuf);
Py_XDECREF(py_retlist);
Py_XDECREF(py_arg);
return NULL;
}
/*
* Return process environment variables as a Python dict
*/
static PyObject *
psutil_proc_environ(PyObject *self, PyObject *args) {
int pid;
PyObject *py_retdict = PyDict_New();
PyObject *py_key = NULL;
PyObject *py_val = NULL;
struct procsinfo procbuf;
long env_max;
char *envbuf = NULL;
char *curvar = NULL;
char *separator = NULL;
int ret;
if (py_retdict == NULL)
return NULL;
if (!PyArg_ParseTuple(args, "i", &pid))
goto error;
env_max = sysconf(_SC_ARG_MAX);
envbuf = malloc(env_max);
if (envbuf == NULL) {
PyErr_NoMemory();
goto error;
}
procbuf.pi_pid = pid;
ret = getevars(&procbuf, sizeof(procbuf), envbuf, ARG_MAX);
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
curvar = envbuf;
/* getevars will always append an extra NULL to end the arg list,
* even if the buffer is not big enough (even though it is supposed
* to be) so the following 'while' is safe */
while (*curvar != '\0') {
separator = strchr(curvar, '=');
if (separator != NULL) {
py_key = PyUnicode_DecodeFSDefaultAndSize(
curvar,
(Py_ssize_t)(separator - curvar)
);
if (!py_key)
goto error;
py_val = PyUnicode_DecodeFSDefault(separator + 1);
if (!py_val)
goto error;
if (PyDict_SetItem(py_retdict, py_key, py_val))
goto error;
Py_CLEAR(py_key);
Py_CLEAR(py_val);
}
curvar = strchr(curvar, '\0') + 1;
}
free(envbuf);
return py_retdict;
error:
if (envbuf != NULL)
free(envbuf);
Py_XDECREF(py_retdict);
Py_XDECREF(py_key);
Py_XDECREF(py_val);
return NULL;
}
#ifdef CURR_VERSION_THREAD
/*
* Retrieves all threads used by process returning a list of tuples
* including thread id, user time and system time.
*/
static PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
long pid;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
perfstat_thread_t *threadt = NULL;
perfstat_id_t id;
int i, rc, thread_count;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "l", &pid))
goto error;
/* Get the count of threads */
thread_count = perfstat_thread(NULL, NULL, sizeof(perfstat_thread_t), 0);
if (thread_count <= 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
/* Allocate enough memory */
threadt = (perfstat_thread_t *)calloc(thread_count,
sizeof(perfstat_thread_t));
if (threadt == NULL) {
PyErr_NoMemory();
goto error;
}
strcpy(id.name, "");
rc = perfstat_thread(&id, threadt, sizeof(perfstat_thread_t),
thread_count);
if (rc <= 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < thread_count; i++) {
if (threadt[i].pid != pid)
continue;
py_tuple = Py_BuildValue("Idd",
threadt[i].tid,
threadt[i].ucpu_time,
threadt[i].scpu_time);
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
free(threadt);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (threadt != NULL)
free(threadt);
return NULL;
}
#endif
#ifdef CURR_VERSION_PROCESS
static PyObject *
psutil_proc_io_counters(PyObject *self, PyObject *args) {
long pid;
int rc;
perfstat_process_t procinfo;
perfstat_id_t id;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
snprintf(id.name, sizeof(id.name), "%ld", pid);
rc = perfstat_process(&id, &procinfo, sizeof(perfstat_process_t), 1);
if (rc <= 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue("(KKKK)",
procinfo.inOps, // XXX always 0
procinfo.outOps,
procinfo.inBytes, // XXX always 0
procinfo.outBytes);
}
#endif
/*
* Return process user and system CPU times as a Python tuple.
*/
static PyObject *
psutil_proc_cpu_times(PyObject *self, PyObject *args) {
int pid;
char path[100];
pstatus_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/status", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
// results are more precise than os.times()
return Py_BuildValue("dddd",
TV2DOUBLE(info.pr_utime),
TV2DOUBLE(info.pr_stime),
TV2DOUBLE(info.pr_cutime),
TV2DOUBLE(info.pr_cstime));
}
/*
* Return process uids/gids as a Python tuple.
*/
static PyObject *
psutil_proc_cred(PyObject *self, PyObject *args) {
int pid;
char path[100];
prcred_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/cred", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
return Py_BuildValue("iiiiii",
info.pr_ruid, info.pr_euid, info.pr_suid,
info.pr_rgid, info.pr_egid, info.pr_sgid);
}
/*
* Return process voluntary and involuntary context switches as a Python tuple.
*/
static PyObject *
psutil_proc_num_ctx_switches(PyObject *self, PyObject *args) {
PyObject *py_tuple = NULL;
pid32_t requested_pid;
pid32_t pid = 0;
int np = 0;
struct procentry64 *processes = (struct procentry64 *)NULL;
struct procentry64 *p;
if (! PyArg_ParseTuple(args, "i", &requested_pid))
return NULL;
processes = psutil_read_process_table(&np);
if (!processes)
return NULL;
/* Loop through processes */
for (p = processes; np > 0; np--, p++) {
pid = p->pi_pid;
if (requested_pid != pid)
continue;
py_tuple = Py_BuildValue("LL",
(long long) p->pi_ru.ru_nvcsw, /* voluntary context switches */
(long long) p->pi_ru.ru_nivcsw); /* involuntary */
free(processes);
return py_tuple;
}
/* finished iteration without finding requested pid */
free(processes);
return NoSuchProcess("psutil_read_process_table (no PID found)");
}
/*
* Return users currently connected on the system.
*/
static PyObject *
psutil_users(PyObject *self, PyObject *args) {
struct utmpx *ut;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_user_proc = NULL;
if (py_retlist == NULL)
return NULL;
setutxent();
while (NULL != (ut = getutxent())) {
if (ut->ut_type == USER_PROCESS)
py_user_proc = Py_True;
else
py_user_proc = Py_False;
py_username = PyUnicode_DecodeFSDefault(ut->ut_user);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(ut->ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(ut->ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"(OOOdOi)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)ut->ut_tv.tv_sec, // tstamp
py_user_proc, // (bool) user process
ut->ut_pid // process id
);
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
}
endutxent();
return py_retlist;
error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (ut != NULL)
endutxent();
return NULL;
}
/*
* Return disk mounted partitions as a list of tuples including device,
* mount point and filesystem type.
*/
static PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
FILE *file = NULL;
struct mntent * mt = NULL;
PyObject *py_dev = NULL;
PyObject *py_mountp = NULL;
PyObject *py_tuple = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
file = setmntent(MNTTAB, "rb");
if (file == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
mt = getmntent(file);
while (mt != NULL) {
py_dev = PyUnicode_DecodeFSDefault(mt->mnt_fsname);
if (! py_dev)
goto error;
py_mountp = PyUnicode_DecodeFSDefault(mt->mnt_dir);
if (! py_mountp)
goto error;
py_tuple = Py_BuildValue(
"(OOss)",
py_dev, // device
py_mountp, // mount point
mt->mnt_type, // fs type
mt->mnt_opts); // options
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_dev);
Py_CLEAR(py_mountp);
Py_CLEAR(py_tuple);
mt = getmntent(file);
}
endmntent(file);
return py_retlist;
error:
Py_XDECREF(py_dev);
Py_XDECREF(py_mountp);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (file != NULL)
endmntent(file);
return NULL;
}
#if defined(CURR_VERSION_NETINTERFACE) && CURR_VERSION_NETINTERFACE >= 3
/*
* Return a list of tuples for network I/O statistics.
*/
static PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args) {
perfstat_netinterface_t *statp = NULL;
int tot, i;
perfstat_id_t first;
PyObject *py_retdict = PyDict_New();
PyObject *py_ifc_info = NULL;
if (py_retdict == NULL)
return NULL;
/* check how many perfstat_netinterface_t structures are available */
tot = perfstat_netinterface(
NULL, NULL, sizeof(perfstat_netinterface_t), 0);
if (tot == 0) {
// no network interfaces - return empty dict
return py_retdict;
}
if (tot < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
statp = (perfstat_netinterface_t *)
malloc(tot * sizeof(perfstat_netinterface_t));
if (statp == NULL) {
PyErr_NoMemory();
goto error;
}
strcpy(first.name, FIRST_NETINTERFACE);
tot = perfstat_netinterface(&first, statp,
sizeof(perfstat_netinterface_t), tot);
if (tot < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < tot; i++) {
py_ifc_info = Py_BuildValue("(KKKKKKKK)",
statp[i].obytes, /* number of bytes sent on interface */
statp[i].ibytes, /* number of bytes received on interface */
statp[i].opackets, /* number of packets sent on interface */
statp[i].ipackets, /* number of packets received on interface */
statp[i].ierrors, /* number of input errors on interface */
statp[i].oerrors, /* number of output errors on interface */
statp[i].if_iqdrops, /* Dropped on input, this interface */
statp[i].xmitdrops /* number of packets not transmitted */
);
if (!py_ifc_info)
goto error;
if (PyDict_SetItemString(py_retdict, statp[i].name, py_ifc_info))
goto error;
Py_DECREF(py_ifc_info);
}
free(statp);
return py_retdict;
error:
if (statp != NULL)
free(statp);
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
return NULL;
}
#endif
static PyObject*
psutil_net_if_stats(PyObject* self, PyObject* args) {
char *nic_name;
int sock = 0;
int ret;
int mtu;
struct ifreq ifr;
PyObject *py_is_up = NULL;
PyObject *py_retlist = NULL;
if (! PyArg_ParseTuple(args, "s", &nic_name))
return NULL;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
goto error;
PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
// is up?
ret = ioctl(sock, SIOCGIFFLAGS, &ifr);
if (ret == -1)
goto error;
if ((ifr.ifr_flags & IFF_UP) != 0)
py_is_up = Py_True;
else
py_is_up = Py_False;
Py_INCREF(py_is_up);
// MTU
ret = ioctl(sock, SIOCGIFMTU, &ifr);
if (ret == -1)
goto error;
mtu = ifr.ifr_mtu;
close(sock);
py_retlist = Py_BuildValue("[Oi]", py_is_up, mtu);
if (!py_retlist)
goto error;
Py_DECREF(py_is_up);
return py_retlist;
error:
Py_XDECREF(py_is_up);
if (sock != 0)
close(sock);
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
static PyObject *
psutil_boot_time(PyObject *self, PyObject *args) {
float boot_time = 0.0;
struct utmpx *ut;
setutxent();
while (NULL != (ut = getutxent())) {
if (ut->ut_type == BOOT_TIME) {
boot_time = (float)ut->ut_tv.tv_sec;
break;
}
}
endutxent();
if (boot_time == 0.0) {
/* could not find BOOT_TIME in getutxent loop */
PyErr_SetString(PyExc_RuntimeError, "can't determine boot time");
return NULL;
}
return Py_BuildValue("f", boot_time);
}
/*
* Return a Python list of tuple representing per-cpu times
*/
static PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
int ncpu, rc, i;
long ticks;
perfstat_cpu_t *cpu = NULL;
perfstat_id_t id;
PyObject *py_retlist = PyList_New(0);
PyObject *py_cputime = NULL;
if (py_retlist == NULL)
return NULL;
/* get the number of ticks per second */
ticks = sysconf(_SC_CLK_TCK);
if (ticks < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
/* get the number of cpus in ncpu */
ncpu = perfstat_cpu(NULL, NULL, sizeof(perfstat_cpu_t), 0);
if (ncpu <= 0){
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
/* allocate enough memory to hold the ncpu structures */
cpu = (perfstat_cpu_t *) malloc(ncpu * sizeof(perfstat_cpu_t));
if (cpu == NULL) {
PyErr_NoMemory();
goto error;
}
strcpy(id.name, "");
rc = perfstat_cpu(&id, cpu, sizeof(perfstat_cpu_t), ncpu);
if (rc <= 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < ncpu; i++) {
py_cputime = Py_BuildValue(
"(dddd)",
(double)cpu[i].user / ticks,
(double)cpu[i].sys / ticks,
(double)cpu[i].idle / ticks,
(double)cpu[i].wait / ticks);
if (!py_cputime)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_DECREF(py_cputime);
}
free(cpu);
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
if (cpu != NULL)
free(cpu);
return NULL;
}
/*
* Return disk IO statistics.
*/
static PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
PyObject *py_retdict = PyDict_New();
PyObject *py_disk_info = NULL;
perfstat_disk_t *diskt = NULL;
perfstat_id_t id;
int i, rc, disk_count;
if (py_retdict == NULL)
return NULL;
/* Get the count of disks */
disk_count = perfstat_disk(NULL, NULL, sizeof(perfstat_disk_t), 0);
if (disk_count <= 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
/* Allocate enough memory */
diskt = (perfstat_disk_t *)calloc(disk_count,
sizeof(perfstat_disk_t));
if (diskt == NULL) {
PyErr_NoMemory();
goto error;
}
strcpy(id.name, FIRST_DISK);
rc = perfstat_disk(&id, diskt, sizeof(perfstat_disk_t),
disk_count);
if (rc <= 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < disk_count; i++) {
py_disk_info = Py_BuildValue(
"KKKKKK",
diskt[i].__rxfers,
diskt[i].xfers - diskt[i].__rxfers,
diskt[i].rblks * diskt[i].bsize,
diskt[i].wblks * diskt[i].bsize,
diskt[i].rserv / 1000 / 1000, // from nano to milli secs
diskt[i].wserv / 1000 / 1000 // from nano to milli secs
);
if (py_disk_info == NULL)
goto error;
if (PyDict_SetItemString(py_retdict, diskt[i].name,
py_disk_info))
goto error;
Py_DECREF(py_disk_info);
}
free(diskt);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (diskt != NULL)
free(diskt);
return NULL;
}
/*
* Return virtual memory usage statistics.
*/
static PyObject *
psutil_virtual_mem(PyObject *self, PyObject *args) {
int rc;
long pagesize = psutil_getpagesize();
perfstat_memory_total_t memory;
rc = perfstat_memory_total(
NULL, &memory, sizeof(perfstat_memory_total_t), 1);
if (rc <= 0){
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue("KKKKK",
(unsigned long long) memory.real_total * pagesize,
(unsigned long long) memory.real_avail * pagesize,
(unsigned long long) memory.real_free * pagesize,
(unsigned long long) memory.real_pinned * pagesize,
(unsigned long long) memory.real_inuse * pagesize
);
}
/*
* Return stats about swap memory.
*/
static PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
int rc;
long pagesize = psutil_getpagesize();
perfstat_memory_total_t memory;
rc = perfstat_memory_total(
NULL, &memory, sizeof(perfstat_memory_total_t), 1);
if (rc <= 0){
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue("KKKK",
(unsigned long long) memory.pgsp_total * pagesize,
(unsigned long long) memory.pgsp_free * pagesize,
(unsigned long long) memory.pgins * pagesize,
(unsigned long long) memory.pgouts * pagesize
);
}
/*
* Return CPU statistics.
*/
static PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
int ncpu, rc, i;
// perfstat_cpu_total_t doesn't have invol/vol cswitch, only pswitch
// which is apparently something else. We have to sum over all cpus
perfstat_cpu_t *cpu = NULL;
perfstat_id_t id;
u_longlong_t cswitches = 0;
u_longlong_t devintrs = 0;
u_longlong_t softintrs = 0;
u_longlong_t syscall = 0;
/* get the number of cpus in ncpu */
ncpu = perfstat_cpu(NULL, NULL, sizeof(perfstat_cpu_t), 0);
if (ncpu <= 0){
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
/* allocate enough memory to hold the ncpu structures */
cpu = (perfstat_cpu_t *) malloc(ncpu * sizeof(perfstat_cpu_t));
if (cpu == NULL) {
PyErr_NoMemory();
goto error;
}
strcpy(id.name, "");
rc = perfstat_cpu(&id, cpu, sizeof(perfstat_cpu_t), ncpu);
if (rc <= 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < ncpu; i++) {
cswitches += cpu[i].invol_cswitch + cpu[i].vol_cswitch;
devintrs += cpu[i].devintrs;
softintrs += cpu[i].softintrs;
syscall += cpu[i].syscall;
}
free(cpu);
return Py_BuildValue(
"KKKK",
cswitches,
devintrs,
softintrs,
syscall
);
error:
if (cpu != NULL)
free(cpu);
return NULL;
}
/*
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef
PsutilMethods[] =
{
// --- process-related functions
{"proc_args", psutil_proc_args, METH_VARARGS},
{"proc_basic_info", psutil_proc_basic_info, METH_VARARGS},
{"proc_cpu_times", psutil_proc_cpu_times, METH_VARARGS},
{"proc_cred", psutil_proc_cred, METH_VARARGS},
{"proc_environ", psutil_proc_environ, METH_VARARGS},
{"proc_name", psutil_proc_name, METH_VARARGS},
#ifdef CURR_VERSION_THREAD
{"proc_threads", psutil_proc_threads, METH_VARARGS},
#endif
#ifdef CURR_VERSION_PROCESS
{"proc_io_counters", psutil_proc_io_counters, METH_VARARGS},
#endif
{"proc_num_ctx_switches", psutil_proc_num_ctx_switches, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"swap_mem", psutil_swap_mem, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"virtual_mem", psutil_virtual_mem, METH_VARARGS},
#if defined(CURR_VERSION_NETINTERFACE) && CURR_VERSION_NETINTERFACE >= 3
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
#endif
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"net_connections", psutil_net_connections, METH_VARARGS},
{"net_if_stats", psutil_net_if_stats, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
struct module_state {
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if PY_MAJOR_VERSION >= 3
static int
psutil_aix_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(GETSTATE(m)->error);
return 0;
}
static int
psutil_aix_clear(PyObject *m) {
Py_CLEAR(GETSTATE(m)->error);
return 0;
}
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"psutil_aix",
NULL,
sizeof(struct module_state),
PsutilMethods,
NULL,
psutil_aix_traverse,
psutil_aix_clear,
NULL
};
#define INITERROR return NULL
PyMODINIT_FUNC PyInit__psutil_aix(void)
#else
#define INITERROR return
void init_psutil_aix(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule("_psutil_aix", PsutilMethods);
#endif
PyModule_AddIntConstant(module, "version", PSUTIL_VERSION);
PyModule_AddIntConstant(module, "SIDL", SIDL);
PyModule_AddIntConstant(module, "SZOMB", SZOMB);
PyModule_AddIntConstant(module, "SACTIVE", SACTIVE);
PyModule_AddIntConstant(module, "SSWAP", SSWAP);
PyModule_AddIntConstant(module, "SSTOP", SSTOP);
PyModule_AddIntConstant(module, "TCPS_CLOSED", TCPS_CLOSED);
PyModule_AddIntConstant(module, "TCPS_CLOSING", TCPS_CLOSING);
PyModule_AddIntConstant(module, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT);
PyModule_AddIntConstant(module, "TCPS_LISTEN", TCPS_LISTEN);
PyModule_AddIntConstant(module, "TCPS_ESTABLISHED", TCPS_ESTABLISHED);
PyModule_AddIntConstant(module, "TCPS_SYN_SENT", TCPS_SYN_SENT);
PyModule_AddIntConstant(module, "TCPS_SYN_RCVD", TCPS_SYN_RECEIVED);
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1);
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2);
PyModule_AddIntConstant(module, "TCPS_LAST_ACK", TCPS_LAST_ACK);
PyModule_AddIntConstant(module, "TCPS_TIME_WAIT", TCPS_TIME_WAIT);
PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
psutil_setup();
if (module == NULL)
INITERROR;
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
#ifdef __cplusplus
}
#endif
| 30,210 | 26.046553 | 79 | c |
psutil | psutil-master/psutil/_psutil_bsd.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola', Landry Breuil
* (OpenBSD implementation), Ryo Onodera (NetBSD implementation).
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Platform-specific module methods for FreeBSD and OpenBSD.
* OpenBSD references:
* - OpenBSD source code: https://github.com/openbsd/src
*
* OpenBSD / NetBSD: missing APIs compared to FreeBSD implementation:
* - psutil.net_connections()
* - psutil.Process.get/set_cpu_affinity() (not supported natively)
* - psutil.Process.memory_maps()
*/
#include <Python.h>
#include <sys/proc.h>
#include <sys/param.h> // BSD version
#include <netinet/tcp_fsm.h> // for TCP connection states
#include "_psutil_common.h"
#include "_psutil_posix.h"
#include "arch/bsd/cpu.h"
#include "arch/bsd/disk.h"
#include "arch/bsd/net.h"
#include "arch/bsd/proc.h"
#include "arch/bsd/sys.h"
#ifdef PSUTIL_FREEBSD
#include "arch/freebsd/cpu.h"
#include "arch/freebsd/disk.h"
#include "arch/freebsd/mem.h"
#include "arch/freebsd/proc.h"
#include "arch/freebsd/proc_socks.h"
#include "arch/freebsd/sensors.h"
#include "arch/freebsd/sys_socks.h"
#elif PSUTIL_OPENBSD
#include "arch/openbsd/cpu.h"
#include "arch/openbsd/disk.h"
#include "arch/openbsd/mem.h"
#include "arch/openbsd/proc.h"
#include "arch/openbsd/socks.h"
#elif PSUTIL_NETBSD
#include "arch/netbsd/cpu.h"
#include "arch/netbsd/disk.h"
#include "arch/netbsd/mem.h"
#include "arch/netbsd/proc.h"
#include "arch/netbsd/socks.h"
#endif
/*
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef mod_methods[] = {
// --- per-process functions
{"proc_cmdline", psutil_proc_cmdline, METH_VARARGS},
{"proc_name", psutil_proc_name, METH_VARARGS},
{"proc_oneshot_info", psutil_proc_oneshot_info, METH_VARARGS},
{"proc_threads", psutil_proc_threads, METH_VARARGS},
#if defined(PSUTIL_FREEBSD)
{"proc_connections", psutil_proc_connections, METH_VARARGS},
#endif
{"proc_cwd", psutil_proc_cwd, METH_VARARGS},
#if defined(__FreeBSD_version) && __FreeBSD_version >= 800000 || PSUTIL_OPENBSD || defined(PSUTIL_NETBSD)
{"proc_num_fds", psutil_proc_num_fds, METH_VARARGS},
{"proc_open_files", psutil_proc_open_files, METH_VARARGS},
#endif
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_NETBSD)
{"proc_num_threads", psutil_proc_num_threads, METH_VARARGS},
#endif
#if defined(PSUTIL_FREEBSD)
{"cpu_topology", psutil_cpu_topology, METH_VARARGS},
{"proc_cpu_affinity_get", psutil_proc_cpu_affinity_get, METH_VARARGS},
{"proc_cpu_affinity_set", psutil_proc_cpu_affinity_set, METH_VARARGS},
{"proc_exe", psutil_proc_exe, METH_VARARGS},
{"proc_getrlimit", psutil_proc_getrlimit, METH_VARARGS},
{"proc_memory_maps", psutil_proc_memory_maps, METH_VARARGS},
{"proc_setrlimit", psutil_proc_setrlimit, METH_VARARGS},
#endif
{"proc_environ", psutil_proc_environ, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"cpu_count_logical", psutil_cpu_count_logical, METH_VARARGS},
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"cpu_times", psutil_cpu_times, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"net_connections", psutil_net_connections, METH_VARARGS},
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"pids", psutil_pids, METH_VARARGS},
{"swap_mem", psutil_swap_mem, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"virtual_mem", psutil_virtual_mem, METH_VARARGS},
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_OPENBSD)
{"cpu_freq", psutil_cpu_freq, METH_VARARGS},
#endif
#if defined(PSUTIL_FREEBSD)
{"sensors_battery", psutil_sensors_battery, METH_VARARGS},
{"sensors_cpu_temperature", psutil_sensors_cpu_temperature, METH_VARARGS},
#endif
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERR return NULL
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_psutil_bsd",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit__psutil_bsd(void)
#else /* PY_MAJOR_VERSION */
#define INITERR return
void init_psutil_bsd(void)
#endif /* PY_MAJOR_VERSION */
{
PyObject *v;
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_bsd", mod_methods);
#endif
if (mod == NULL)
INITERR;
if (PyModule_AddIntConstant(mod, "version", PSUTIL_VERSION)) INITERR;
// process status constants
#ifdef PSUTIL_FREEBSD
if (PyModule_AddIntConstant(mod, "SIDL", SIDL)) INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", SRUN)) INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", SSLEEP)) INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", SSTOP)) INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", SZOMB)) INITERR;
if (PyModule_AddIntConstant(mod, "SWAIT", SWAIT)) INITERR;
if (PyModule_AddIntConstant(mod, "SLOCK", SLOCK)) INITERR;
#elif PSUTIL_OPENBSD
if (PyModule_AddIntConstant(mod, "SIDL", SIDL)) INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", SRUN)) INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", SSLEEP)) INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", SSTOP)) INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", SZOMB)) INITERR; // unused
if (PyModule_AddIntConstant(mod, "SDEAD", SDEAD)) INITERR;
if (PyModule_AddIntConstant(mod, "SONPROC", SONPROC)) INITERR;
#elif defined(PSUTIL_NETBSD)
if (PyModule_AddIntConstant(mod, "SIDL", LSIDL)) INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", LSRUN)) INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", LSSLEEP)) INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", LSSTOP)) INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", LSZOMB)) INITERR;
#if __NetBSD_Version__ < 500000000
if (PyModule_AddIntConstant(mod, "SDEAD", LSDEAD)) INITERR;
#endif
if (PyModule_AddIntConstant(mod, "SONPROC", LSONPROC)) INITERR;
// unique to NetBSD
if (PyModule_AddIntConstant(mod, "SSUSPENDED", LSSUSPENDED)) INITERR;
#endif
// connection status constants
if (PyModule_AddIntConstant(mod, "TCPS_CLOSED", TCPS_CLOSED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSING", TCPS_CLOSING))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LISTEN", TCPS_LISTEN))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_ESTABLISHED", TCPS_ESTABLISHED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_SENT", TCPS_SYN_SENT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LAST_ACK", TCPS_LAST_ACK))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_TIME_WAIT", TCPS_TIME_WAIT))
INITERR;
// PSUTIL_CONN_NONE
if (PyModule_AddIntConstant(mod, "PSUTIL_CONN_NONE", 128)) INITERR;
psutil_setup();
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
}
| 7,772 | 35.492958 | 105 | c |
psutil | psutil-master/psutil/_psutil_common.c | /*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Routines common to all platforms.
*/
#include <Python.h>
#include "_psutil_common.h"
// ====================================================================
// --- Global vars
// ====================================================================
int PSUTIL_DEBUG = 0;
// ====================================================================
// --- Backward compatibility with missing Python.h APIs
// ====================================================================
// PyPy on Windows
#if defined(PSUTIL_WINDOWS) && defined(PYPY_VERSION)
#if !defined(PyErr_SetFromWindowsErrWithFilename)
PyObject *
PyErr_SetFromWindowsErrWithFilename(int winerr, const char *filename) {
PyObject *py_exc = NULL;
PyObject *py_winerr = NULL;
if (winerr == 0)
winerr = GetLastError();
if (filename == NULL) {
py_exc = PyObject_CallFunction(PyExc_OSError, "(is)", winerr,
strerror(winerr));
}
else {
py_exc = PyObject_CallFunction(PyExc_OSError, "(iss)", winerr,
strerror(winerr), filename);
}
if (py_exc == NULL)
return NULL;
py_winerr = Py_BuildValue("i", winerr);
if (py_winerr == NULL)
goto error;
if (PyObject_SetAttrString(py_exc, "winerror", py_winerr) != 0)
goto error;
PyErr_SetObject(PyExc_OSError, py_exc);
Py_XDECREF(py_exc);
return NULL;
error:
Py_XDECREF(py_exc);
Py_XDECREF(py_winerr);
return NULL;
}
#endif // !defined(PyErr_SetFromWindowsErrWithFilename)
// PyPy 2.7
#if !defined(PyErr_SetFromWindowsErr)
PyObject *
PyErr_SetFromWindowsErr(int winerr) {
return PyErr_SetFromWindowsErrWithFilename(winerr, "");
}
#endif // !defined(PyErr_SetFromWindowsErr)
#endif // defined(PSUTIL_WINDOWS) && defined(PYPY_VERSION)
// ====================================================================
// --- Custom exceptions
// ====================================================================
/*
* Same as PyErr_SetFromErrno(0) but adds the syscall to the exception
* message.
*/
PyObject *
PyErr_SetFromOSErrnoWithSyscall(const char *syscall) {
char fullmsg[1024];
#ifdef PSUTIL_WINDOWS
DWORD dwLastError = GetLastError();
sprintf(fullmsg, "(originated from %s)", syscall);
PyErr_SetFromWindowsErrWithFilename(dwLastError, fullmsg);
#else
PyObject *exc;
sprintf(fullmsg, "%s (originated from %s)", strerror(errno), syscall);
exc = PyObject_CallFunction(PyExc_OSError, "(is)", errno, fullmsg);
PyErr_SetObject(PyExc_OSError, exc);
Py_XDECREF(exc);
#endif
return NULL;
}
/*
* Set OSError(errno=ESRCH, strerror="No such process (originated from")
* Python exception.
*/
PyObject *
NoSuchProcess(const char *syscall) {
PyObject *exc;
char msg[1024];
sprintf(msg, "assume no such process (originated from %s)", syscall);
exc = PyObject_CallFunction(PyExc_OSError, "(is)", ESRCH, msg);
PyErr_SetObject(PyExc_OSError, exc);
Py_XDECREF(exc);
return NULL;
}
/*
* Set OSError(errno=EACCES, strerror="Permission denied" (originated from ...)
* Python exception.
*/
PyObject *
AccessDenied(const char *syscall) {
PyObject *exc;
char msg[1024];
sprintf(msg, "assume access denied (originated from %s)", syscall);
exc = PyObject_CallFunction(PyExc_OSError, "(is)", EACCES, msg);
PyErr_SetObject(PyExc_OSError, exc);
Py_XDECREF(exc);
return NULL;
}
/*
* Raise OverflowError if Python int value overflowed when converting to pid_t.
* Raise ValueError if Python int value is negative.
* Otherwise, return None.
*/
PyObject *
psutil_check_pid_range(PyObject *self, PyObject *args) {
#ifdef PSUTIL_WINDOWS
DWORD pid;
#else
pid_t pid;
#endif
if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (pid < 0) {
PyErr_SetString(PyExc_ValueError, "pid must be a positive integer");
return NULL;
}
Py_RETURN_NONE;
}
// Enable or disable PSUTIL_DEBUG messages.
PyObject *
psutil_set_debug(PyObject *self, PyObject *args) {
PyObject *value;
int x;
if (!PyArg_ParseTuple(args, "O", &value))
return NULL;
x = PyObject_IsTrue(value);
if (x < 0) {
return NULL;
}
else if (x == 0) {
PSUTIL_DEBUG = 0;
}
else {
PSUTIL_DEBUG = 1;
}
Py_RETURN_NONE;
}
// ============================================================================
// Utility functions (BSD)
// ============================================================================
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
void
convert_kvm_err(const char *syscall, char *errbuf) {
char fullmsg[8192];
sprintf(fullmsg, "(originated from %s: %s)", syscall, errbuf);
if (strstr(errbuf, "Permission denied") != NULL)
AccessDenied(fullmsg);
else if (strstr(errbuf, "Operation not permitted") != NULL)
AccessDenied(fullmsg);
else
PyErr_Format(PyExc_RuntimeError, fullmsg);
}
#endif
// ====================================================================
// --- macOS
// ====================================================================
#ifdef PSUTIL_OSX
#include <mach/mach_time.h>
struct mach_timebase_info PSUTIL_MACH_TIMEBASE_INFO;
#endif
// ====================================================================
// --- Windows
// ====================================================================
#ifdef PSUTIL_WINDOWS
#include <windows.h>
// Needed to make these globally visible.
int PSUTIL_WINVER;
SYSTEM_INFO PSUTIL_SYSTEM_INFO;
CRITICAL_SECTION PSUTIL_CRITICAL_SECTION;
// A wrapper around GetModuleHandle and GetProcAddress.
PVOID
psutil_GetProcAddress(LPCSTR libname, LPCSTR procname) {
HMODULE mod;
FARPROC addr;
if ((mod = GetModuleHandleA(libname)) == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, libname);
return NULL;
}
if ((addr = GetProcAddress(mod, procname)) == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, procname);
return NULL;
}
return addr;
}
// A wrapper around LoadLibrary and GetProcAddress.
PVOID
psutil_GetProcAddressFromLib(LPCSTR libname, LPCSTR procname) {
HMODULE mod;
FARPROC addr;
Py_BEGIN_ALLOW_THREADS
mod = LoadLibraryA(libname);
Py_END_ALLOW_THREADS
if (mod == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, libname);
return NULL;
}
if ((addr = GetProcAddress(mod, procname)) == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, procname);
FreeLibrary(mod);
return NULL;
}
// Causes crash.
// FreeLibrary(mod);
return addr;
}
/*
* Convert a NTSTATUS value to a Win32 error code and set the proper
* Python exception.
*/
PVOID
psutil_SetFromNTStatusErr(NTSTATUS Status, const char *syscall) {
ULONG err;
char fullmsg[1024];
if (NT_NTWIN32(Status))
err = WIN32_FROM_NTSTATUS(Status);
else
err = RtlNtStatusToDosErrorNoTeb(Status);
// if (GetLastError() != 0)
// err = GetLastError();
sprintf(fullmsg, "(originated from %s)", syscall);
return PyErr_SetFromWindowsErrWithFilename(err, fullmsg);
}
static int
psutil_loadlibs() {
// --- Mandatory
NtQuerySystemInformation = psutil_GetProcAddressFromLib(
"ntdll.dll", "NtQuerySystemInformation");
if (! NtQuerySystemInformation)
return 1;
NtQueryInformationProcess = psutil_GetProcAddress(
"ntdll.dll", "NtQueryInformationProcess");
if (! NtQueryInformationProcess)
return 1;
NtSetInformationProcess = psutil_GetProcAddress(
"ntdll.dll", "NtSetInformationProcess");
if (! NtSetInformationProcess)
return 1;
NtQueryObject = psutil_GetProcAddressFromLib(
"ntdll.dll", "NtQueryObject");
if (! NtQueryObject)
return 1;
RtlIpv4AddressToStringA = psutil_GetProcAddressFromLib(
"ntdll.dll", "RtlIpv4AddressToStringA");
if (! RtlIpv4AddressToStringA)
return 1;
GetExtendedTcpTable = psutil_GetProcAddressFromLib(
"iphlpapi.dll", "GetExtendedTcpTable");
if (! GetExtendedTcpTable)
return 1;
GetExtendedUdpTable = psutil_GetProcAddressFromLib(
"iphlpapi.dll", "GetExtendedUdpTable");
if (! GetExtendedUdpTable)
return 1;
RtlGetVersion = psutil_GetProcAddressFromLib(
"ntdll.dll", "RtlGetVersion");
if (! RtlGetVersion)
return 1;
NtSuspendProcess = psutil_GetProcAddressFromLib(
"ntdll", "NtSuspendProcess");
if (! NtSuspendProcess)
return 1;
NtResumeProcess = psutil_GetProcAddressFromLib(
"ntdll", "NtResumeProcess");
if (! NtResumeProcess)
return 1;
NtQueryVirtualMemory = psutil_GetProcAddressFromLib(
"ntdll", "NtQueryVirtualMemory");
if (! NtQueryVirtualMemory)
return 1;
RtlNtStatusToDosErrorNoTeb = psutil_GetProcAddressFromLib(
"ntdll", "RtlNtStatusToDosErrorNoTeb");
if (! RtlNtStatusToDosErrorNoTeb)
return 1;
GetTickCount64 = psutil_GetProcAddress(
"kernel32", "GetTickCount64");
if (! GetTickCount64)
return 1;
RtlIpv6AddressToStringA = psutil_GetProcAddressFromLib(
"ntdll.dll", "RtlIpv6AddressToStringA");
if (! RtlIpv6AddressToStringA)
return 1;
// --- Optional
// minimum requirement: Win 7
GetActiveProcessorCount = psutil_GetProcAddress(
"kernel32", "GetActiveProcessorCount");
// minimum requirement: Win 7
GetLogicalProcessorInformationEx = psutil_GetProcAddressFromLib(
"kernel32", "GetLogicalProcessorInformationEx");
// minimum requirements: Windows Server Core
WTSEnumerateSessionsW = psutil_GetProcAddressFromLib(
"wtsapi32.dll", "WTSEnumerateSessionsW");
WTSQuerySessionInformationW = psutil_GetProcAddressFromLib(
"wtsapi32.dll", "WTSQuerySessionInformationW");
WTSFreeMemory = psutil_GetProcAddressFromLib(
"wtsapi32.dll", "WTSFreeMemory");
PyErr_Clear();
return 0;
}
static int
psutil_set_winver() {
RTL_OSVERSIONINFOEXW versionInfo;
ULONG maj;
ULONG min;
versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
memset(&versionInfo, 0, sizeof(RTL_OSVERSIONINFOEXW));
RtlGetVersion((PRTL_OSVERSIONINFOW)&versionInfo);
maj = versionInfo.dwMajorVersion;
min = versionInfo.dwMinorVersion;
if (maj == 6 && min == 0)
PSUTIL_WINVER = PSUTIL_WINDOWS_VISTA; // or Server 2008
else if (maj == 6 && min == 1)
PSUTIL_WINVER = PSUTIL_WINDOWS_7;
else if (maj == 6 && min == 2)
PSUTIL_WINVER = PSUTIL_WINDOWS_8;
else if (maj == 6 && min == 3)
PSUTIL_WINVER = PSUTIL_WINDOWS_8_1;
else if (maj == 10 && min == 0)
PSUTIL_WINVER = PSUTIL_WINDOWS_10;
else
PSUTIL_WINVER = PSUTIL_WINDOWS_NEW;
return 0;
}
/*
* Convert the hi and lo parts of a FILETIME structure or a LARGE_INTEGER
* to a UNIX time.
* A FILETIME contains a 64-bit value representing the number of
* 100-nanosecond intervals since January 1, 1601 (UTC).
* A UNIX time is the number of seconds that have elapsed since the
* UNIX epoch, that is the time 00:00:00 UTC on 1 January 1970.
*/
static double
_to_unix_time(ULONGLONG hiPart, ULONGLONG loPart) {
ULONGLONG ret;
// 100 nanosecond intervals since January 1, 1601.
ret = hiPart << 32;
ret += loPart;
// Change starting time to the Epoch (00:00:00 UTC, January 1, 1970).
ret -= 116444736000000000ull;
// Convert nano secs to secs.
return (double) ret / 10000000ull;
}
double
psutil_FiletimeToUnixTime(FILETIME ft) {
return _to_unix_time((ULONGLONG)ft.dwHighDateTime,
(ULONGLONG)ft.dwLowDateTime);
}
double
psutil_LargeIntegerToUnixTime(LARGE_INTEGER li) {
return _to_unix_time((ULONGLONG)li.HighPart,
(ULONGLONG)li.LowPart);
}
#endif // PSUTIL_WINDOWS
// Called on module import on all platforms.
int
psutil_setup(void) {
if (getenv("PSUTIL_DEBUG") != NULL)
PSUTIL_DEBUG = 1;
#ifdef PSUTIL_WINDOWS
if (psutil_loadlibs() != 0)
return 1;
if (psutil_set_winver() != 0)
return 1;
GetSystemInfo(&PSUTIL_SYSTEM_INFO);
InitializeCriticalSection(&PSUTIL_CRITICAL_SECTION);
#endif
#ifdef PSUTIL_OSX
mach_timebase_info(&PSUTIL_MACH_TIMEBASE_INFO);
#endif
return 0;
}
| 12,644 | 27.608597 | 80 | c |
psutil | psutil-master/psutil/_psutil_common.h | /*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
// ====================================================================
// --- Global vars / constants
// ====================================================================
extern int PSUTIL_DEBUG;
// a signaler for connections without an actual status
static const int PSUTIL_CONN_NONE = 128;
// strncpy() variant which appends a null terminator.
#define PSUTIL_STRNCPY(dst, src, n) \
strncpy(dst, src, n - 1); \
dst[n - 1] = '\0'
// ====================================================================
// --- Backward compatibility with missing Python.h APIs
// ====================================================================
#if PY_MAJOR_VERSION < 3
// On Python 2 we just return a plain byte string, which is never
// supposed to raise decoding errors, see:
// https://github.com/giampaolo/psutil/issues/1040
#define PyUnicode_DecodeFSDefault PyString_FromString
#define PyUnicode_DecodeFSDefaultAndSize PyString_FromStringAndSize
#endif
#if defined(PSUTIL_WINDOWS) && \
defined(PYPY_VERSION) && \
!defined(PyErr_SetFromWindowsErrWithFilename)
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr,
const char *filename);
#endif
// --- _Py_PARSE_PID
// SIZEOF_INT|LONG is missing on Linux + PyPy (only?).
// SIZEOF_PID_T is missing on Windows + Python2.
// In this case we guess it from setup.py. It's not 100% bullet proof,
// If wrong we'll probably get compiler warnings.
// FWIW on all UNIX platforms I've seen pid_t is defined as an int.
// _getpid() on Windows also returns an int.
#if !defined(SIZEOF_INT)
#define SIZEOF_INT 4
#endif
#if !defined(SIZEOF_LONG)
#define SIZEOF_LONG 8
#endif
#if !defined(SIZEOF_PID_T)
#define SIZEOF_PID_T PSUTIL_SIZEOF_PID_T // set as a macro in setup.py
#endif
// _Py_PARSE_PID is Python 3 only, but since it's private make sure it's
// always present.
#ifndef _Py_PARSE_PID
#if SIZEOF_PID_T == SIZEOF_INT
#define _Py_PARSE_PID "i"
#elif SIZEOF_PID_T == SIZEOF_LONG
#define _Py_PARSE_PID "l"
#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
#define _Py_PARSE_PID "L"
#else
#error "_Py_PARSE_PID: sizeof(pid_t) is neither sizeof(int), "
"sizeof(long) or sizeof(long long)"
#endif
#endif
// Python 2 or PyPy on Windows
#ifndef PyLong_FromPid
#if ((SIZEOF_PID_T == SIZEOF_INT) || (SIZEOF_PID_T == SIZEOF_LONG))
#if PY_MAJOR_VERSION >= 3
#define PyLong_FromPid PyLong_FromLong
#else
#define PyLong_FromPid PyInt_FromLong
#endif
#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
#define PyLong_FromPid PyLong_FromLongLong
#else
#error "PyLong_FromPid: sizeof(pid_t) is neither sizeof(int), "
"sizeof(long) or sizeof(long long)"
#endif
#endif
// ====================================================================
// --- Custom exceptions
// ====================================================================
PyObject* AccessDenied(const char *msg);
PyObject* NoSuchProcess(const char *msg);
PyObject* PyErr_SetFromOSErrnoWithSyscall(const char *syscall);
// ====================================================================
// --- Global utils
// ====================================================================
PyObject* psutil_check_pid_range(PyObject *self, PyObject *args);
PyObject* psutil_set_debug(PyObject *self, PyObject *args);
int psutil_setup(void);
// Print a debug message on stderr.
#define psutil_debug(...) do { \
if (! PSUTIL_DEBUG) \
break; \
fprintf(stderr, "psutil-debug [%s:%d]> ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n");} while(0)
// ====================================================================
// --- BSD
// ====================================================================
void convert_kvm_err(const char *syscall, char *errbuf);
// ====================================================================
// --- macOS
// ====================================================================
#ifdef PSUTIL_OSX
#include <mach/mach_time.h>
extern struct mach_timebase_info PSUTIL_MACH_TIMEBASE_INFO;
#endif
// ====================================================================
// --- Windows
// ====================================================================
#ifdef PSUTIL_WINDOWS
#include <windows.h>
// make it available to any file which includes this module
#include "arch/windows/ntextapi.h"
extern int PSUTIL_WINVER;
extern SYSTEM_INFO PSUTIL_SYSTEM_INFO;
extern CRITICAL_SECTION PSUTIL_CRITICAL_SECTION;
#define PSUTIL_WINDOWS_VISTA 60
#define PSUTIL_WINDOWS_7 61
#define PSUTIL_WINDOWS_8 62
#define PSUTIL_WINDOWS_8_1 63
#define PSUTIL_WINDOWS_10 100
#define PSUTIL_WINDOWS_NEW MAXLONG
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define MALLOC_ZERO(x) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
#define _NT_FACILITY_MASK 0xfff
#define _NT_FACILITY_SHIFT 16
#define _NT_FACILITY(status) \
((((ULONG)(status)) >> _NT_FACILITY_SHIFT) & _NT_FACILITY_MASK)
#define NT_NTWIN32(status) (_NT_FACILITY(status) == FACILITY_WIN32)
#define WIN32_FROM_NTSTATUS(status) (((ULONG)(status)) & 0xffff)
#define LO_T 1e-7
#define HI_T 429.4967296
#ifndef AF_INET6
#define AF_INET6 23
#endif
PVOID psutil_GetProcAddress(LPCSTR libname, LPCSTR procname);
PVOID psutil_GetProcAddressFromLib(LPCSTR libname, LPCSTR procname);
PVOID psutil_SetFromNTStatusErr(NTSTATUS Status, const char *syscall);
double psutil_FiletimeToUnixTime(FILETIME ft);
double psutil_LargeIntegerToUnixTime(LARGE_INTEGER li);
#endif
| 6,118 | 33.570621 | 77 | h |
psutil | psutil-master/psutil/_psutil_linux.c | /*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Linux-specific functions.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <Python.h>
#include <errno.h>
#include <stdlib.h>
#include <mntent.h>
#include <features.h>
#include <utmp.h>
#include <sched.h>
#include <linux/version.h>
#include <sys/syscall.h>
#include <sys/sysinfo.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/sockios.h>
#include <linux/if.h>
#include <sys/resource.h>
// see: https://github.com/giampaolo/psutil/issues/659
#ifdef PSUTIL_ETHTOOL_MISSING_TYPES
#include <linux/types.h>
typedef __u64 u64;
typedef __u32 u32;
typedef __u16 u16;
typedef __u8 u8;
#endif
/* Avoid redefinition of struct sysinfo with musl libc */
#define _LINUX_SYSINFO_H
#include <linux/ethtool.h>
/* The minimum number of CPUs allocated in a cpu_set_t */
static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
// Linux >= 2.6.13
#define PSUTIL_HAVE_IOPRIO defined(__NR_ioprio_get) && defined(__NR_ioprio_set)
// Should exist starting from CentOS 6 (year 2011).
#ifdef CPU_ALLOC
#define PSUTIL_HAVE_CPU_AFFINITY
#endif
#include "_psutil_common.h"
#include "_psutil_posix.h"
// May happen on old RedHat versions, see:
// https://github.com/giampaolo/psutil/issues/607
#ifndef DUPLEX_UNKNOWN
#define DUPLEX_UNKNOWN 0xff
#endif
#ifndef SPEED_UNKNOWN
#define SPEED_UNKNOWN -1
#endif
#if PSUTIL_HAVE_IOPRIO
enum {
IOPRIO_WHO_PROCESS = 1,
};
static inline int
ioprio_get(int which, int who) {
return syscall(__NR_ioprio_get, which, who);
}
static inline int
ioprio_set(int which, int who, int ioprio) {
return syscall(__NR_ioprio_set, which, who, ioprio);
}
// * defined in linux/ethtool.h but not always available (e.g. Android)
// * #ifdef check needed for old kernels, see:
// https://github.com/giampaolo/psutil/issues/2164
static inline uint32_t
psutil_ethtool_cmd_speed(const struct ethtool_cmd *ecmd) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 27)
return ecmd->speed;
#else
return (ecmd->speed_hi << 16) | ecmd->speed;
#endif
}
#define IOPRIO_CLASS_SHIFT 13
#define IOPRIO_PRIO_MASK ((1UL << IOPRIO_CLASS_SHIFT) - 1)
#define IOPRIO_PRIO_CLASS(mask) ((mask) >> IOPRIO_CLASS_SHIFT)
#define IOPRIO_PRIO_DATA(mask) ((mask) & IOPRIO_PRIO_MASK)
#define IOPRIO_PRIO_VALUE(class, data) (((class) << IOPRIO_CLASS_SHIFT) | data)
/*
* Return a (ioclass, iodata) Python tuple representing process I/O priority.
*/
static PyObject *
psutil_proc_ioprio_get(PyObject *self, PyObject *args) {
pid_t pid;
int ioprio, ioclass, iodata;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
ioprio = ioprio_get(IOPRIO_WHO_PROCESS, pid);
if (ioprio == -1)
return PyErr_SetFromErrno(PyExc_OSError);
ioclass = IOPRIO_PRIO_CLASS(ioprio);
iodata = IOPRIO_PRIO_DATA(ioprio);
return Py_BuildValue("ii", ioclass, iodata);
}
/*
* A wrapper around ioprio_set(); sets process I/O priority.
* ioclass can be either IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE
* or 0. iodata goes from 0 to 7 depending on ioclass specified.
*/
static PyObject *
psutil_proc_ioprio_set(PyObject *self, PyObject *args) {
pid_t pid;
int ioprio, ioclass, iodata;
int retval;
if (! PyArg_ParseTuple(
args, _Py_PARSE_PID "ii", &pid, &ioclass, &iodata)) {
return NULL;
}
ioprio = IOPRIO_PRIO_VALUE(ioclass, iodata);
retval = ioprio_set(IOPRIO_WHO_PROCESS, pid, ioprio);
if (retval == -1)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
}
#endif
/*
* Return disk mounted partitions as a list of tuples including device,
* mount point and filesystem type
*/
static PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
FILE *file = NULL;
struct mntent *entry;
char *mtab_path;
PyObject *py_dev = NULL;
PyObject *py_mountp = NULL;
PyObject *py_tuple = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (!PyArg_ParseTuple(args, "s", &mtab_path))
return NULL;
Py_BEGIN_ALLOW_THREADS
file = setmntent(mtab_path, "r");
Py_END_ALLOW_THREADS
if ((file == 0) || (file == NULL)) {
psutil_debug("setmntent() failed");
PyErr_SetFromErrnoWithFilename(PyExc_OSError, mtab_path);
goto error;
}
while ((entry = getmntent(file))) {
if (entry == NULL) {
PyErr_Format(PyExc_RuntimeError, "getmntent() syscall failed");
goto error;
}
py_dev = PyUnicode_DecodeFSDefault(entry->mnt_fsname);
if (! py_dev)
goto error;
py_mountp = PyUnicode_DecodeFSDefault(entry->mnt_dir);
if (! py_mountp)
goto error;
py_tuple = Py_BuildValue("(OOss)",
py_dev, // device
py_mountp, // mount point
entry->mnt_type, // fs type
entry->mnt_opts); // options
if (! py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_dev);
Py_CLEAR(py_mountp);
Py_CLEAR(py_tuple);
}
endmntent(file);
return py_retlist;
error:
if (file != NULL)
endmntent(file);
Py_XDECREF(py_dev);
Py_XDECREF(py_mountp);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
return NULL;
}
/*
* A wrapper around sysinfo(), return system memory usage statistics.
*/
static PyObject *
psutil_linux_sysinfo(PyObject *self, PyObject *args) {
struct sysinfo info;
if (sysinfo(&info) != 0)
return PyErr_SetFromErrno(PyExc_OSError);
// note: boot time might also be determined from here
return Py_BuildValue(
"(kkkkkkI)",
info.totalram, // total
info.freeram, // free
info.bufferram, // buffer
info.sharedram, // shared
info.totalswap, // swap tot
info.freeswap, // swap free
info.mem_unit // multiplier
);
}
/*
* Return process CPU affinity as a Python list
*/
#ifdef PSUTIL_HAVE_CPU_AFFINITY
static PyObject *
psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) {
int cpu, ncpus, count, cpucount_s;
pid_t pid;
size_t setsize;
cpu_set_t *mask = NULL;
PyObject *py_list = NULL;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
ncpus = NCPUS_START;
while (1) {
setsize = CPU_ALLOC_SIZE(ncpus);
mask = CPU_ALLOC(ncpus);
if (mask == NULL) {
psutil_debug("CPU_ALLOC() failed");
return PyErr_NoMemory();
}
if (sched_getaffinity(pid, setsize, mask) == 0)
break;
CPU_FREE(mask);
if (errno != EINVAL)
return PyErr_SetFromErrno(PyExc_OSError);
if (ncpus > INT_MAX / 2) {
PyErr_SetString(PyExc_OverflowError, "could not allocate "
"a large enough CPU set");
return NULL;
}
ncpus = ncpus * 2;
}
py_list = PyList_New(0);
if (py_list == NULL)
goto error;
cpucount_s = CPU_COUNT_S(setsize, mask);
for (cpu = 0, count = cpucount_s; count; cpu++) {
if (CPU_ISSET_S(cpu, setsize, mask)) {
#if PY_MAJOR_VERSION >= 3
PyObject *cpu_num = PyLong_FromLong(cpu);
#else
PyObject *cpu_num = PyInt_FromLong(cpu);
#endif
if (cpu_num == NULL)
goto error;
if (PyList_Append(py_list, cpu_num)) {
Py_DECREF(cpu_num);
goto error;
}
Py_DECREF(cpu_num);
--count;
}
}
CPU_FREE(mask);
return py_list;
error:
if (mask)
CPU_FREE(mask);
Py_XDECREF(py_list);
return NULL;
}
/*
* Set process CPU affinity; expects a bitmask
*/
static PyObject *
psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
cpu_set_t cpu_set;
size_t len;
pid_t pid;
Py_ssize_t i, seq_len;
PyObject *py_cpu_set;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &py_cpu_set))
return NULL;
if (!PySequence_Check(py_cpu_set)) {
return PyErr_Format(
PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"sequence argument expected, got %R", Py_TYPE(py_cpu_set)
#else
"sequence argument expected, got %s", Py_TYPE(py_cpu_set)->tp_name
#endif
);
}
seq_len = PySequence_Size(py_cpu_set);
if (seq_len < 0) {
return NULL;
}
CPU_ZERO(&cpu_set);
for (i = 0; i < seq_len; i++) {
PyObject *item = PySequence_GetItem(py_cpu_set, i);
if (!item) {
return NULL;
}
#if PY_MAJOR_VERSION >= 3
long value = PyLong_AsLong(item);
#else
long value = PyInt_AsLong(item);
#endif
Py_XDECREF(item);
if ((value == -1) || PyErr_Occurred()) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError, "invalid CPU value");
return NULL;
}
CPU_SET(value, &cpu_set);
}
len = sizeof(cpu_set);
if (sched_setaffinity(pid, len, &cpu_set)) {
return PyErr_SetFromErrno(PyExc_OSError);
}
Py_RETURN_NONE;
}
#endif /* PSUTIL_HAVE_CPU_AFFINITY */
/*
* Return currently connected users as a list of tuples.
*/
static PyObject *
psutil_users(PyObject *self, PyObject *args) {
struct utmp *ut;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_user_proc = NULL;
if (py_retlist == NULL)
return NULL;
setutent();
while (NULL != (ut = getutent())) {
py_tuple = NULL;
py_user_proc = NULL;
if (ut->ut_type == USER_PROCESS)
py_user_proc = Py_True;
else
py_user_proc = Py_False;
py_username = PyUnicode_DecodeFSDefault(ut->ut_user);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(ut->ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(ut->ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"OOOdO" _Py_PARSE_PID,
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)ut->ut_tv.tv_sec, // tstamp
py_user_proc, // (bool) user process
ut->ut_pid // process id
);
if (! py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
}
endutent();
return py_retlist;
error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
endutent();
return NULL;
}
/*
* Return stats about a particular network
* interface. References:
* https://github.com/dpaleino/wicd/blob/master/wicd/backends/be-ioctl.py
* http://www.i-scream.org/libstatgrab/
*/
static PyObject*
psutil_net_if_duplex_speed(PyObject* self, PyObject* args) {
char *nic_name;
int sock = 0;
int ret;
int duplex;
__u32 uint_speed;
int speed;
struct ifreq ifr;
struct ethtool_cmd ethcmd;
PyObject *py_retlist = NULL;
if (! PyArg_ParseTuple(args, "s", &nic_name))
return NULL;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
return PyErr_SetFromOSErrnoWithSyscall("socket()");
PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
// duplex and speed
memset(ðcmd, 0, sizeof ethcmd);
ethcmd.cmd = ETHTOOL_GSET;
ifr.ifr_data = (void *)ðcmd;
ret = ioctl(sock, SIOCETHTOOL, &ifr);
if (ret != -1) {
duplex = ethcmd.duplex;
// speed is returned from ethtool as a __u32 ranging from 0 to INT_MAX
// or SPEED_UNKNOWN (-1)
uint_speed = psutil_ethtool_cmd_speed(ðcmd);
if (uint_speed == (__u32)SPEED_UNKNOWN || uint_speed > INT_MAX) {
speed = 0;
}
else {
speed = (int)uint_speed;
}
}
else {
if ((errno == EOPNOTSUPP) || (errno == EINVAL)) {
// EOPNOTSUPP may occur in case of wi-fi cards.
// For EINVAL see:
// https://github.com/giampaolo/psutil/issues/797
// #issuecomment-202999532
duplex = DUPLEX_UNKNOWN;
speed = 0;
}
else {
PyErr_SetFromOSErrnoWithSyscall("ioctl(SIOCETHTOOL)");
goto error;
}
}
py_retlist = Py_BuildValue("[ii]", duplex, speed);
if (!py_retlist)
goto error;
close(sock);
return py_retlist;
error:
if (sock != -1)
close(sock);
return NULL;
}
/*
* Module init.
*/
static PyMethodDef mod_methods[] = {
// --- per-process functions
#if PSUTIL_HAVE_IOPRIO
{"proc_ioprio_get", psutil_proc_ioprio_get, METH_VARARGS},
{"proc_ioprio_set", psutil_proc_ioprio_set, METH_VARARGS},
#endif
#ifdef PSUTIL_HAVE_CPU_AFFINITY
{"proc_cpu_affinity_get", psutil_proc_cpu_affinity_get, METH_VARARGS},
{"proc_cpu_affinity_set", psutil_proc_cpu_affinity_set, METH_VARARGS},
#endif
// --- system related functions
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"net_if_duplex_speed", psutil_net_if_duplex_speed, METH_VARARGS},
// --- linux specific
{"linux_sysinfo", psutil_linux_sysinfo, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERR return NULL
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_psutil_linux",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit__psutil_linux(void)
#else /* PY_MAJOR_VERSION */
#define INITERR return
void init_psutil_linux(void)
#endif /* PY_MAJOR_VERSION */
{
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_linux", mod_methods);
#endif
if (mod == NULL)
INITERR;
if (PyModule_AddIntConstant(mod, "version", PSUTIL_VERSION)) INITERR;
if (PyModule_AddIntConstant(mod, "DUPLEX_HALF", DUPLEX_HALF)) INITERR;
if (PyModule_AddIntConstant(mod, "DUPLEX_FULL", DUPLEX_FULL)) INITERR;
if (PyModule_AddIntConstant(mod, "DUPLEX_UNKNOWN", DUPLEX_UNKNOWN)) INITERR;
psutil_setup();
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
}
| 15,257 | 25.721541 | 80 | c |
psutil | psutil-master/psutil/_psutil_osx.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* macOS platform-specific module methods.
*/
#include <Python.h>
#include <sys/proc.h>
#include <netinet/tcp_fsm.h>
#include "_psutil_common.h"
#include "arch/osx/cpu.h"
#include "arch/osx/disk.h"
#include "arch/osx/mem.h"
#include "arch/osx/net.h"
#include "arch/osx/proc.h"
#include "arch/osx/sensors.h"
#include "arch/osx/sys.h"
static PyMethodDef mod_methods[] = {
// --- per-process functions
{"proc_cmdline", psutil_proc_cmdline, METH_VARARGS},
{"proc_connections", psutil_proc_connections, METH_VARARGS},
{"proc_cwd", psutil_proc_cwd, METH_VARARGS},
{"proc_environ", psutil_proc_environ, METH_VARARGS},
{"proc_exe", psutil_proc_exe, METH_VARARGS},
{"proc_kinfo_oneshot", psutil_proc_kinfo_oneshot, METH_VARARGS},
{"proc_memory_uss", psutil_proc_memory_uss, METH_VARARGS},
{"proc_name", psutil_proc_name, METH_VARARGS},
{"proc_num_fds", psutil_proc_num_fds, METH_VARARGS},
{"proc_open_files", psutil_proc_open_files, METH_VARARGS},
{"proc_pidtaskinfo_oneshot", psutil_proc_pidtaskinfo_oneshot, METH_VARARGS},
{"proc_threads", psutil_proc_threads, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"cpu_count_cores", psutil_cpu_count_cores, METH_VARARGS},
{"cpu_count_logical", psutil_cpu_count_logical, METH_VARARGS},
{"cpu_freq", psutil_cpu_freq, METH_VARARGS},
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"cpu_times", psutil_cpu_times, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"disk_usage_used", psutil_disk_usage_used, METH_VARARGS},
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"pids", psutil_pids, METH_VARARGS},
{"sensors_battery", psutil_sensors_battery, METH_VARARGS},
{"swap_mem", psutil_swap_mem, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"virtual_mem", psutil_virtual_mem, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERR return NULL
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_psutil_osx",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit__psutil_osx(void)
#else /* PY_MAJOR_VERSION */
#define INITERR return
void init_psutil_osx(void)
#endif /* PY_MAJOR_VERSION */
{
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_osx", mod_methods);
#endif
if (mod == NULL)
INITERR;
if (psutil_setup() != 0)
INITERR;
if (PyModule_AddIntConstant(mod, "version", PSUTIL_VERSION))
INITERR;
// process status constants, defined in:
// http://fxr.watson.org/fxr/source/bsd/sys/proc.h?v=xnu-792.6.70#L149
if (PyModule_AddIntConstant(mod, "SIDL", SIDL))
INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", SRUN))
INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", SSLEEP))
INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", SSTOP))
INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", SZOMB))
INITERR;
// connection status constants
if (PyModule_AddIntConstant(mod, "TCPS_CLOSED", TCPS_CLOSED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSING", TCPS_CLOSING))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LISTEN", TCPS_LISTEN))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_ESTABLISHED", TCPS_ESTABLISHED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_SENT", TCPS_SYN_SENT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LAST_ACK", TCPS_LAST_ACK))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_TIME_WAIT", TCPS_TIME_WAIT))
INITERR;
if (PyModule_AddIntConstant(mod, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE))
INITERR;
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
}
| 4,821 | 32.72028 | 80 | c |
psutil | psutil-master/psutil/_psutil_posix.c | /*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Functions specific to all POSIX compliant platforms.
*/
#include <Python.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#ifdef PSUTIL_SUNOS10
#include "arch/solaris/v10/ifaddrs.h"
#elif PSUTIL_AIX
#include "arch/aix/ifaddrs.h"
#else
#include <ifaddrs.h>
#endif
#if defined(PSUTIL_LINUX)
#include <netdb.h>
#include <linux/types.h>
#include <linux/if_packet.h>
#endif
#if defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
#include <netdb.h>
#include <netinet/in.h>
#include <net/if_dl.h>
#include <sys/sockio.h>
#include <net/if_media.h>
#include <net/if.h>
#endif
#if defined(PSUTIL_SUNOS)
#include <netdb.h>
#include <sys/sockio.h>
#endif
#if defined(PSUTIL_AIX)
#include <netdb.h>
#endif
#if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
#include <sys/resource.h>
#endif
#include "_psutil_common.h"
// ====================================================================
// --- Utils
// ====================================================================
/*
* From "man getpagesize" on Linux, https://linux.die.net/man/2/getpagesize:
*
* > In SUSv2 the getpagesize() call is labeled LEGACY, and in POSIX.1-2001
* > it has been dropped.
* > Portable applications should employ sysconf(_SC_PAGESIZE) instead
* > of getpagesize().
* > Most systems allow the synonym _SC_PAGE_SIZE for _SC_PAGESIZE.
* > Whether getpagesize() is present as a Linux system call depends on the
* > architecture.
*/
long
psutil_getpagesize(void) {
#ifdef _SC_PAGESIZE
// recommended POSIX
return sysconf(_SC_PAGESIZE);
#elif _SC_PAGE_SIZE
// alias
return sysconf(_SC_PAGE_SIZE);
#else
// legacy
return (long) getpagesize();
#endif
}
/*
* Check if PID exists. Return values:
* 1: exists
* 0: does not exist
* -1: error (Python exception is set)
*/
int
psutil_pid_exists(pid_t pid) {
int ret;
// No negative PID exists, plus -1 is an alias for sending signal
// too all processes except system ones. Not what we want.
if (pid < 0)
return 0;
// As per "man 2 kill" PID 0 is an alias for sending the signal to
// every process in the process group of the calling process.
// Not what we want. Some platforms have PID 0, some do not.
// We decide that at runtime.
if (pid == 0) {
#if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
return 0;
#else
return 1;
#endif
}
ret = kill(pid , 0);
if (ret == 0)
return 1;
else {
if (errno == ESRCH) {
// ESRCH == No such process
return 0;
}
else if (errno == EPERM) {
// EPERM clearly indicates there's a process to deny
// access to.
return 1;
}
else {
// According to "man 2 kill" possible error values are
// (EINVAL, EPERM, ESRCH) therefore we should never get
// here. If we do let's be explicit in considering this
// an error.
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
}
}
/*
* Utility used for those syscalls which do not return a meaningful
* error that we can translate into an exception which makes sense.
* As such, we'll have to guess.
* On UNIX, if errno is set, we return that one (OSError).
* Else, if PID does not exist we assume the syscall failed because
* of that so we raise NoSuchProcess.
* If none of this is true we giveup and raise RuntimeError(msg).
* This will always set a Python exception and return NULL.
*/
void
psutil_raise_for_pid(long pid, char *syscall) {
if (errno != 0)
PyErr_SetFromOSErrnoWithSyscall(syscall);
else if (psutil_pid_exists(pid) == 0)
NoSuchProcess(syscall);
else
PyErr_Format(PyExc_RuntimeError, "%s syscall failed", syscall);
}
// ====================================================================
// --- Python wrappers
// ====================================================================
// Exposed so we can test it against Python's stdlib.
static PyObject *
psutil_getpagesize_pywrapper(PyObject *self, PyObject *args) {
return Py_BuildValue("l", psutil_getpagesize());
}
/*
* Given a PID return process priority as a Python integer.
*/
static PyObject *
psutil_posix_getpriority(PyObject *self, PyObject *args) {
pid_t pid;
int priority;
errno = 0;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
#ifdef PSUTIL_OSX
priority = getpriority(PRIO_PROCESS, (id_t)pid);
#else
priority = getpriority(PRIO_PROCESS, pid);
#endif
if (errno != 0)
return PyErr_SetFromErrno(PyExc_OSError);
return Py_BuildValue("i", priority);
}
/*
* Given a PID and a value change process priority.
*/
static PyObject *
psutil_posix_setpriority(PyObject *self, PyObject *args) {
pid_t pid;
int priority;
int retval;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &priority))
return NULL;
#ifdef PSUTIL_OSX
retval = setpriority(PRIO_PROCESS, (id_t)pid, priority);
#else
retval = setpriority(PRIO_PROCESS, pid, priority);
#endif
if (retval == -1)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
}
/*
* Translate a sockaddr struct into a Python string.
* Return None if address family is not AF_INET* or AF_PACKET.
*/
static PyObject *
psutil_convert_ipaddr(struct sockaddr *addr, int family) {
char buf[NI_MAXHOST];
int err;
int addrlen;
size_t n;
size_t len;
const char *data;
char *ptr;
if (addr == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
else if (family == AF_INET || family == AF_INET6) {
if (family == AF_INET)
addrlen = sizeof(struct sockaddr_in);
else
addrlen = sizeof(struct sockaddr_in6);
err = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
NI_NUMERICHOST);
if (err != 0) {
// XXX we get here on FreeBSD when processing 'lo' / AF_INET6
// broadcast. Not sure what to do other than returning None.
// ifconfig does not show anything BTW.
// PyErr_Format(PyExc_RuntimeError, gai_strerror(err));
// return NULL;
Py_INCREF(Py_None);
return Py_None;
}
else {
return Py_BuildValue("s", buf);
}
}
#ifdef PSUTIL_LINUX
else if (family == AF_PACKET) {
struct sockaddr_ll *lladdr = (struct sockaddr_ll *)addr;
len = lladdr->sll_halen;
data = (const char *)lladdr->sll_addr;
}
#elif defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
else if (addr->sa_family == AF_LINK) {
// Note: prior to Python 3.4 socket module does not expose
// AF_LINK so we'll do.
struct sockaddr_dl *dladdr = (struct sockaddr_dl *)addr;
len = dladdr->sdl_alen;
data = LLADDR(dladdr);
}
#endif
else {
// unknown family
Py_INCREF(Py_None);
return Py_None;
}
// AF_PACKET or AF_LINK
if (len > 0) {
ptr = buf;
for (n = 0; n < len; ++n) {
sprintf(ptr, "%02x:", data[n] & 0xff);
ptr += 3;
}
*--ptr = '\0';
return Py_BuildValue("s", buf);
}
else {
Py_INCREF(Py_None);
return Py_None;
}
}
/*
* Return NICs information a-la ifconfig as a list of tuples.
* TODO: on Solaris we won't get any MAC address.
*/
static PyObject*
psutil_net_if_addrs(PyObject* self, PyObject* args) {
struct ifaddrs *ifaddr, *ifa;
int family;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_address = NULL;
PyObject *py_netmask = NULL;
PyObject *py_broadcast = NULL;
PyObject *py_ptp = NULL;
if (py_retlist == NULL)
return NULL;
if (getifaddrs(&ifaddr) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr)
continue;
family = ifa->ifa_addr->sa_family;
py_address = psutil_convert_ipaddr(ifa->ifa_addr, family);
// If the primary address can't be determined just skip it.
// I've never seen this happen on Linux but I did on FreeBSD.
if (py_address == Py_None)
continue;
if (py_address == NULL)
goto error;
py_netmask = psutil_convert_ipaddr(ifa->ifa_netmask, family);
if (py_netmask == NULL)
goto error;
if (ifa->ifa_flags & IFF_BROADCAST) {
py_broadcast = psutil_convert_ipaddr(ifa->ifa_broadaddr, family);
Py_INCREF(Py_None);
py_ptp = Py_None;
}
else if (ifa->ifa_flags & IFF_POINTOPOINT) {
py_ptp = psutil_convert_ipaddr(ifa->ifa_dstaddr, family);
Py_INCREF(Py_None);
py_broadcast = Py_None;
}
else {
Py_INCREF(Py_None);
Py_INCREF(Py_None);
py_broadcast = Py_None;
py_ptp = Py_None;
}
if ((py_broadcast == NULL) || (py_ptp == NULL))
goto error;
py_tuple = Py_BuildValue(
"(siOOOO)",
ifa->ifa_name,
family,
py_address,
py_netmask,
py_broadcast,
py_ptp
);
if (! py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
Py_CLEAR(py_address);
Py_CLEAR(py_netmask);
Py_CLEAR(py_broadcast);
Py_CLEAR(py_ptp);
}
freeifaddrs(ifaddr);
return py_retlist;
error:
if (ifaddr != NULL)
freeifaddrs(ifaddr);
Py_DECREF(py_retlist);
Py_XDECREF(py_tuple);
Py_XDECREF(py_address);
Py_XDECREF(py_netmask);
Py_XDECREF(py_broadcast);
Py_XDECREF(py_ptp);
return NULL;
}
/*
* Return NIC MTU. References:
* http://www.i-scream.org/libstatgrab/
*/
static PyObject *
psutil_net_if_mtu(PyObject *self, PyObject *args) {
char *nic_name;
int sock = -1;
int ret;
#ifdef PSUTIL_SUNOS10
struct lifreq lifr;
#else
struct ifreq ifr;
#endif
if (! PyArg_ParseTuple(args, "s", &nic_name))
return NULL;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
goto error;
#ifdef PSUTIL_SUNOS10
PSUTIL_STRNCPY(lifr.lifr_name, nic_name, sizeof(lifr.lifr_name));
ret = ioctl(sock, SIOCGIFMTU, &lifr);
#else
PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
ret = ioctl(sock, SIOCGIFMTU, &ifr);
#endif
if (ret == -1)
goto error;
close(sock);
#ifdef PSUTIL_SUNOS10
return Py_BuildValue("i", lifr.lifr_mtu);
#else
return Py_BuildValue("i", ifr.ifr_mtu);
#endif
error:
if (sock != -1)
close(sock);
return PyErr_SetFromErrno(PyExc_OSError);
}
static int
append_flag(PyObject *py_retlist, const char * flag_name)
{
PyObject *py_str = NULL;
#if PY_MAJOR_VERSION >= 3
py_str = PyUnicode_FromString(flag_name);
#else
py_str = PyString_FromString(flag_name);
#endif
if (! py_str)
return 0;
if (PyList_Append(py_retlist, py_str)) {
Py_DECREF(py_str);
return 0;
}
Py_CLEAR(py_str);
return 1;
}
/*
* Get all of the NIC flags and return them.
*/
static PyObject *
psutil_net_if_flags(PyObject *self, PyObject *args) {
char *nic_name;
int sock = -1;
int ret;
struct ifreq ifr;
PyObject *py_retlist = PyList_New(0);
short int flags;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "s", &nic_name))
goto error;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) {
PyErr_SetFromOSErrnoWithSyscall("socket(SOCK_DGRAM)");
goto error;
}
PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
ret = ioctl(sock, SIOCGIFFLAGS, &ifr);
if (ret == -1) {
PyErr_SetFromOSErrnoWithSyscall("ioctl(SIOCGIFFLAGS)");
goto error;
}
close(sock);
sock = -1;
flags = ifr.ifr_flags & 0xFFFF;
// Linux/glibc IFF flags: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/gnu/net/if.h;h=251418f82331c0426e58707fe4473d454893b132;hb=HEAD
// macOS IFF flags: https://opensource.apple.com/source/xnu/xnu-792/bsd/net/if.h.auto.html
// AIX IFF flags: https://www.ibm.com/support/pages/how-hexadecimal-flags-displayed-ifconfig-are-calculated
// FreeBSD IFF flags: https://www.freebsd.org/cgi/man.cgi?query=if_allmulti&apropos=0&sektion=0&manpath=FreeBSD+10-current&format=html
#ifdef IFF_UP
// Available in (at least) Linux, macOS, AIX, BSD
if (flags & IFF_UP)
if (!append_flag(py_retlist, "up"))
goto error;
#endif
#ifdef IFF_BROADCAST
// Available in (at least) Linux, macOS, AIX, BSD
if (flags & IFF_BROADCAST)
if (!append_flag(py_retlist, "broadcast"))
goto error;
#endif
#ifdef IFF_DEBUG
// Available in (at least) Linux, macOS, BSD
if (flags & IFF_DEBUG)
if (!append_flag(py_retlist, "debug"))
goto error;
#endif
#ifdef IFF_LOOPBACK
// Available in (at least) Linux, macOS, BSD
if (flags & IFF_LOOPBACK)
if (!append_flag(py_retlist, "loopback"))
goto error;
#endif
#ifdef IFF_POINTOPOINT
// Available in (at least) Linux, macOS, BSD
if (flags & IFF_POINTOPOINT)
if (!append_flag(py_retlist, "pointopoint"))
goto error;
#endif
#ifdef IFF_NOTRAILERS
// Available in (at least) Linux, macOS, AIX
if (flags & IFF_NOTRAILERS)
if (!append_flag(py_retlist, "notrailers"))
goto error;
#endif
#ifdef IFF_RUNNING
// Available in (at least) Linux, macOS, AIX, BSD
if (flags & IFF_RUNNING)
if (!append_flag(py_retlist, "running"))
goto error;
#endif
#ifdef IFF_NOARP
// Available in (at least) Linux, macOS, BSD
if (flags & IFF_NOARP)
if (!append_flag(py_retlist, "noarp"))
goto error;
#endif
#ifdef IFF_PROMISC
// Available in (at least) Linux, macOS, BSD
if (flags & IFF_PROMISC)
if (!append_flag(py_retlist, "promisc"))
goto error;
#endif
#ifdef IFF_ALLMULTI
// Available in (at least) Linux, macOS, BSD
if (flags & IFF_ALLMULTI)
if (!append_flag(py_retlist, "allmulti"))
goto error;
#endif
#ifdef IFF_MASTER
// Available in (at least) Linux
if (flags & IFF_MASTER)
if (!append_flag(py_retlist, "master"))
goto error;
#endif
#ifdef IFF_SLAVE
// Available in (at least) Linux
if (flags & IFF_SLAVE)
if (!append_flag(py_retlist, "slave"))
goto error;
#endif
#ifdef IFF_MULTICAST
// Available in (at least) Linux, macOS, BSD
if (flags & IFF_MULTICAST)
if (!append_flag(py_retlist, "multicast"))
goto error;
#endif
#ifdef IFF_PORTSEL
// Available in (at least) Linux
if (flags & IFF_PORTSEL)
if (!append_flag(py_retlist, "portsel"))
goto error;
#endif
#ifdef IFF_AUTOMEDIA
// Available in (at least) Linux
if (flags & IFF_AUTOMEDIA)
if (!append_flag(py_retlist, "automedia"))
goto error;
#endif
#ifdef IFF_DYNAMIC
// Available in (at least) Linux
if (flags & IFF_DYNAMIC)
if (!append_flag(py_retlist, "dynamic"))
goto error;
#endif
#ifdef IFF_OACTIVE
// Available in (at least) macOS, BSD
if (flags & IFF_OACTIVE)
if (!append_flag(py_retlist, "oactive"))
goto error;
#endif
#ifdef IFF_SIMPLEX
// Available in (at least) macOS, AIX, BSD
if (flags & IFF_SIMPLEX)
if (!append_flag(py_retlist, "simplex"))
goto error;
#endif
#ifdef IFF_LINK0
// Available in (at least) macOS, BSD
if (flags & IFF_LINK0)
if (!append_flag(py_retlist, "link0"))
goto error;
#endif
#ifdef IFF_LINK1
// Available in (at least) macOS, BSD
if (flags & IFF_LINK1)
if (!append_flag(py_retlist, "link1"))
goto error;
#endif
#ifdef IFF_LINK2
// Available in (at least) macOS, BSD
if (flags & IFF_LINK2)
if (!append_flag(py_retlist, "link2"))
goto error;
#endif
#ifdef IFF_D2
// Available in (at least) AIX
if (flags & IFF_D2)
if (!append_flag(py_retlist, "d2"))
goto error;
#endif
return py_retlist;
error:
Py_DECREF(py_retlist);
if (sock != -1)
close(sock);
return NULL;
}
/*
* Inspect NIC flags, returns a bool indicating whether the NIC is
* running. References:
* http://www.i-scream.org/libstatgrab/
*/
static PyObject *
psutil_net_if_is_running(PyObject *self, PyObject *args) {
char *nic_name;
int sock = -1;
int ret;
struct ifreq ifr;
if (! PyArg_ParseTuple(args, "s", &nic_name))
return NULL;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
goto error;
PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
ret = ioctl(sock, SIOCGIFFLAGS, &ifr);
if (ret == -1)
goto error;
close(sock);
if ((ifr.ifr_flags & IFF_RUNNING) != 0)
return Py_BuildValue("O", Py_True);
else
return Py_BuildValue("O", Py_False);
error:
if (sock != -1)
close(sock);
return PyErr_SetFromErrno(PyExc_OSError);
}
/*
* net_if_stats() macOS/BSD implementation.
*/
#if defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
int psutil_get_nic_speed(int ifm_active) {
// Determine NIC speed. Taken from:
// http://www.i-scream.org/libstatgrab/
// Assuming only ETHER devices
switch(IFM_TYPE(ifm_active)) {
case IFM_ETHER:
switch(IFM_SUBTYPE(ifm_active)) {
#if defined(IFM_HPNA_1) && ((!defined(IFM_10G_LR)) \
|| (IFM_10G_LR != IFM_HPNA_1))
// HomePNA 1.0 (1Mb/s)
case(IFM_HPNA_1):
return 1;
#endif
// 10 Mbit
case(IFM_10_T): // 10BaseT - RJ45
case(IFM_10_2): // 10Base2 - Thinnet
case(IFM_10_5): // 10Base5 - AUI
case(IFM_10_STP): // 10BaseT over shielded TP
case(IFM_10_FL): // 10baseFL - Fiber
return 10;
// 100 Mbit
case(IFM_100_TX): // 100BaseTX - RJ45
case(IFM_100_FX): // 100BaseFX - Fiber
case(IFM_100_T4): // 100BaseT4 - 4 pair cat 3
case(IFM_100_VG): // 100VG-AnyLAN
case(IFM_100_T2): // 100BaseT2
return 100;
// 1000 Mbit
case(IFM_1000_SX): // 1000BaseSX - multi-mode fiber
case(IFM_1000_LX): // 1000baseLX - single-mode fiber
case(IFM_1000_CX): // 1000baseCX - 150ohm STP
#if defined(IFM_1000_TX) && !defined(PSUTIL_OPENBSD)
#define HAS_CASE_IFM_1000_TX 1
// FreeBSD 4 and others (but NOT OpenBSD) -> #define IFM_1000_T in net/if_media.h
case(IFM_1000_TX):
#endif
#ifdef IFM_1000_FX
case(IFM_1000_FX):
#endif
#if defined(IFM_1000_T) && (!HAS_CASE_IFM_1000_TX || IFM_1000_T != IFM_1000_TX)
case(IFM_1000_T):
#endif
return 1000;
#if defined(IFM_10G_SR) || defined(IFM_10G_LR) || defined(IFM_10G_CX4) \
|| defined(IFM_10G_T)
#ifdef IFM_10G_SR
case(IFM_10G_SR):
#endif
#ifdef IFM_10G_LR
case(IFM_10G_LR):
#endif
#ifdef IFM_10G_CX4
case(IFM_10G_CX4):
#endif
#ifdef IFM_10G_TWINAX
case(IFM_10G_TWINAX):
#endif
#ifdef IFM_10G_TWINAX_LONG
case(IFM_10G_TWINAX_LONG):
#endif
#ifdef IFM_10G_T
case(IFM_10G_T):
#endif
return 10000;
#endif
#if defined(IFM_2500_SX)
#ifdef IFM_2500_SX
case(IFM_2500_SX):
#endif
return 2500;
#endif // any 2.5GBit stuff...
// We don't know what it is
default:
return 0;
}
break;
#ifdef IFM_TOKEN
case IFM_TOKEN:
switch(IFM_SUBTYPE(ifm_active)) {
case IFM_TOK_STP4: // Shielded twisted pair 4m - DB9
case IFM_TOK_UTP4: // Unshielded twisted pair 4m - RJ45
return 4;
case IFM_TOK_STP16: // Shielded twisted pair 16m - DB9
case IFM_TOK_UTP16: // Unshielded twisted pair 16m - RJ45
return 16;
#if defined(IFM_TOK_STP100) || defined(IFM_TOK_UTP100)
#ifdef IFM_TOK_STP100
case IFM_TOK_STP100: // Shielded twisted pair 100m - DB9
#endif
#ifdef IFM_TOK_UTP100
case IFM_TOK_UTP100: // Unshielded twisted pair 100m - RJ45
#endif
return 100;
#endif
// We don't know what it is
default:
return 0;
}
break;
#endif
#ifdef IFM_FDDI
case IFM_FDDI:
switch(IFM_SUBTYPE(ifm_active)) {
// We don't know what it is
default:
return 0;
}
break;
#endif
case IFM_IEEE80211:
switch(IFM_SUBTYPE(ifm_active)) {
case IFM_IEEE80211_FH1: // Frequency Hopping 1Mbps
case IFM_IEEE80211_DS1: // Direct Sequence 1Mbps
return 1;
case IFM_IEEE80211_FH2: // Frequency Hopping 2Mbps
case IFM_IEEE80211_DS2: // Direct Sequence 2Mbps
return 2;
case IFM_IEEE80211_DS5: // Direct Sequence 5Mbps
return 5;
case IFM_IEEE80211_DS11: // Direct Sequence 11Mbps
return 11;
case IFM_IEEE80211_DS22: // Direct Sequence 22Mbps
return 22;
// We don't know what it is
default:
return 0;
}
break;
default:
return 0;
}
}
/*
* Return stats about a particular network interface.
* References:
* http://www.i-scream.org/libstatgrab/
*/
static PyObject *
psutil_net_if_duplex_speed(PyObject *self, PyObject *args) {
char *nic_name;
int sock = -1;
int ret;
int duplex;
int speed;
struct ifreq ifr;
struct ifmediareq ifmed;
if (! PyArg_ParseTuple(args, "s", &nic_name))
return NULL;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
return PyErr_SetFromErrno(PyExc_OSError);
PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
// speed / duplex
memset(&ifmed, 0, sizeof(struct ifmediareq));
strlcpy(ifmed.ifm_name, nic_name, sizeof(ifmed.ifm_name));
ret = ioctl(sock, SIOCGIFMEDIA, (caddr_t)&ifmed);
if (ret == -1) {
speed = 0;
duplex = 0;
}
else {
speed = psutil_get_nic_speed(ifmed.ifm_active);
if ((ifmed.ifm_active | IFM_FDX) == ifmed.ifm_active)
duplex = 2;
else if ((ifmed.ifm_active | IFM_HDX) == ifmed.ifm_active)
duplex = 1;
else
duplex = 0;
}
close(sock);
return Py_BuildValue("[ii]", duplex, speed);
}
#endif // net_if_stats() macOS/BSD implementation
#ifdef __cplusplus
extern "C" {
#endif
/*
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef mod_methods[] = {
{"getpagesize", psutil_getpagesize_pywrapper, METH_VARARGS},
{"getpriority", psutil_posix_getpriority, METH_VARARGS},
{"net_if_addrs", psutil_net_if_addrs, METH_VARARGS},
{"net_if_flags", psutil_net_if_flags, METH_VARARGS},
{"net_if_is_running", psutil_net_if_is_running, METH_VARARGS},
{"net_if_mtu", psutil_net_if_mtu, METH_VARARGS},
{"setpriority", psutil_posix_setpriority, METH_VARARGS},
#if defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
{"net_if_duplex_speed", psutil_net_if_duplex_speed, METH_VARARGS},
#endif
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERR return NULL
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_psutil_posix",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit__psutil_posix(void)
#else /* PY_MAJOR_VERSION */
#define INITERR return
void init_psutil_posix(void)
#endif /* PY_MAJOR_VERSION */
{
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_posix", mod_methods);
#endif
if (mod == NULL)
INITERR;
#if defined(PSUTIL_BSD) || \
defined(PSUTIL_OSX) || \
defined(PSUTIL_SUNOS) || \
defined(PSUTIL_AIX)
if (PyModule_AddIntConstant(mod, "AF_LINK", AF_LINK)) INITERR;
#endif
#if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
PyObject *v;
#ifdef RLIMIT_AS
if (PyModule_AddIntConstant(mod, "RLIMIT_AS", RLIMIT_AS)) INITERR;
#endif
#ifdef RLIMIT_CORE
if (PyModule_AddIntConstant(mod, "RLIMIT_CORE", RLIMIT_CORE)) INITERR;
#endif
#ifdef RLIMIT_CPU
if (PyModule_AddIntConstant(mod, "RLIMIT_CPU", RLIMIT_CPU)) INITERR;
#endif
#ifdef RLIMIT_DATA
if (PyModule_AddIntConstant(mod, "RLIMIT_DATA", RLIMIT_DATA)) INITERR;
#endif
#ifdef RLIMIT_FSIZE
if (PyModule_AddIntConstant(mod, "RLIMIT_FSIZE", RLIMIT_FSIZE)) INITERR;
#endif
#ifdef RLIMIT_MEMLOCK
if (PyModule_AddIntConstant(mod, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK)) INITERR;
#endif
#ifdef RLIMIT_NOFILE
if (PyModule_AddIntConstant(mod, "RLIMIT_NOFILE", RLIMIT_NOFILE)) INITERR;
#endif
#ifdef RLIMIT_NPROC
if (PyModule_AddIntConstant(mod, "RLIMIT_NPROC", RLIMIT_NPROC)) INITERR;
#endif
#ifdef RLIMIT_RSS
if (PyModule_AddIntConstant(mod, "RLIMIT_RSS", RLIMIT_RSS)) INITERR;
#endif
#ifdef RLIMIT_STACK
if (PyModule_AddIntConstant(mod, "RLIMIT_STACK", RLIMIT_STACK)) INITERR;
#endif
// Linux specific
#ifdef RLIMIT_LOCKS
if (PyModule_AddIntConstant(mod, "RLIMIT_LOCKS", RLIMIT_LOCKS)) INITERR;
#endif
#ifdef RLIMIT_MSGQUEUE
if (PyModule_AddIntConstant(mod, "RLIMIT_MSGQUEUE", RLIMIT_MSGQUEUE)) INITERR;
#endif
#ifdef RLIMIT_NICE
if (PyModule_AddIntConstant(mod, "RLIMIT_NICE", RLIMIT_NICE)) INITERR;
#endif
#ifdef RLIMIT_RTPRIO
if (PyModule_AddIntConstant(mod, "RLIMIT_RTPRIO", RLIMIT_RTPRIO)) INITERR;
#endif
#ifdef RLIMIT_RTTIME
if (PyModule_AddIntConstant(mod, "RLIMIT_RTTIME", RLIMIT_RTTIME)) INITERR;
#endif
#ifdef RLIMIT_SIGPENDING
if (PyModule_AddIntConstant(mod, "RLIMIT_SIGPENDING", RLIMIT_SIGPENDING)) INITERR;
#endif
// Free specific
#ifdef RLIMIT_SWAP
if (PyModule_AddIntConstant(mod, "RLIMIT_SWAP", RLIMIT_SWAP)) INITERR;
#endif
#ifdef RLIMIT_SBSIZE
if (PyModule_AddIntConstant(mod, "RLIMIT_SBSIZE", RLIMIT_SBSIZE)) INITERR;
#endif
#ifdef RLIMIT_NPTS
if (PyModule_AddIntConstant(mod, "RLIMIT_NPTS", RLIMIT_NPTS)) INITERR;
#endif
#if defined(HAVE_LONG_LONG)
if (sizeof(RLIM_INFINITY) > sizeof(long)) {
v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
} else
#endif
{
v = PyLong_FromLong((long) RLIM_INFINITY);
}
if (v) {
PyModule_AddObject(mod, "RLIM_INFINITY", v);
}
#endif // defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
}
#ifdef __cplusplus
}
#endif
| 27,849 | 26.065112 | 150 | c |
psutil | psutil-master/psutil/_psutil_posix.h | /*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
long psutil_getpagesize(void);
int psutil_pid_exists(pid_t pid);
void psutil_raise_for_pid(pid_t pid, char *msg);
| 289 | 28 | 73 | h |
psutil | psutil-master/psutil/_psutil_sunos.c | /*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Functions specific to Sun OS Solaris platforms.
*
* Thanks to Justin Venus who originally wrote a consistent part of
* this in Cython which I later on translated in C.
*/
/* fix compilation issue on SunOS 5.10, see:
* https://github.com/giampaolo/psutil/issues/421
* https://github.com/giampaolo/psutil/issues/1077
*/
#define _STRUCTURED_PROC 1
#include <Python.h>
#if !defined(_LP64) && _FILE_OFFSET_BITS == 64
# undef _FILE_OFFSET_BITS
# undef _LARGEFILE64_SOURCE
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/proc.h>
#include <sys/swap.h>
#include <sys/sysinfo.h>
#include <sys/mntent.h> // for MNTTAB
#include <sys/mnttab.h>
#include <sys/procfs.h>
#include <sys/sockio.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <utmpx.h>
#include <kstat.h>
#include <sys/ioctl.h>
#include <sys/tihdr.h>
#include <stropts.h>
#include <inet/tcp.h>
#ifndef NEW_MIB_COMPLIANT
/*
* Solaris introduced NEW_MIB_COMPLIANT macro with Update 4.
* See https://github.com/giampaolo/psutil/issues/421
* Prior to Update 4, one has to include mib2 by hand.
*/
#include <inet/mib2.h>
#endif
#include <arpa/inet.h>
#include <net/if.h>
#include <math.h> // fabs()
#include "_psutil_common.h"
#include "_psutil_posix.h"
#include "arch/solaris/environ.h"
#define PSUTIL_TV2DOUBLE(t) (((t).tv_nsec * 0.000000001) + (t).tv_sec)
/*
* Read a file content and fills a C structure with it.
*/
static int
psutil_file_to_struct(char *path, void *fstruct, size_t size) {
int fd;
ssize_t nbytes;
fd = open(path, O_RDONLY);
if (fd == -1) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
return 0;
}
nbytes = read(fd, fstruct, size);
if (nbytes == -1) {
close(fd);
PyErr_SetFromErrno(PyExc_OSError);
return 0;
}
if (nbytes != (ssize_t) size) {
close(fd);
PyErr_SetString(
PyExc_RuntimeError, "read() file structure size mismatch");
return 0;
}
close(fd);
return nbytes;
}
/*
* Return process ppid, rss, vms, ctime, nice, nthreads, status and tty
* as a Python tuple.
*/
static PyObject *
psutil_proc_basic_info(PyObject *self, PyObject *args) {
int pid;
char path[1000];
psinfo_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/psinfo", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
return Py_BuildValue(
"ikkdiiikiiii",
info.pr_ppid, // parent pid
info.pr_rssize, // rss
info.pr_size, // vms
PSUTIL_TV2DOUBLE(info.pr_start), // create time
info.pr_lwp.pr_nice, // nice
info.pr_nlwp, // no. of threads
info.pr_lwp.pr_state, // status code
info.pr_ttydev, // tty nr
(int)info.pr_uid, // real user id
(int)info.pr_euid, // effective user id
(int)info.pr_gid, // real group id
(int)info.pr_egid // effective group id
);
}
/*
* Join array of C strings to C string with delimiter dm.
* Omit empty records.
*/
static int
cstrings_array_to_string(char **joined, char ** array, size_t count, char dm) {
size_t i;
size_t total_length = 0;
size_t item_length = 0;
char *result = NULL;
char *last = NULL;
if (!array || !joined)
return 0;
for (i=0; i<count; i++) {
if (!array[i])
continue;
item_length = strlen(array[i]) + 1;
total_length += item_length;
}
if (!total_length) {
return 0;
}
result = malloc(total_length);
if (!result) {
PyErr_NoMemory();
return -1;
}
result[0] = '\0';
last = result;
for (i=0; i<count; i++) {
if (!array[i])
continue;
item_length = strlen(array[i]);
memcpy(last, array[i], item_length);
last[item_length] = dm;
last += item_length + 1;
}
result[total_length-1] = '\0';
*joined = result;
return total_length;
}
/*
* Return process name and args as a Python tuple.
*/
static PyObject *
psutil_proc_name_and_args(PyObject *self, PyObject *args) {
int pid;
char path[1000];
psinfo_t info;
size_t argc;
int joined;
char **argv;
char *argv_plain;
const char *procfs_path;
PyObject *py_name = NULL;
PyObject *py_args = NULL;
PyObject *py_retlist = NULL;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/psinfo", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
py_name = PyUnicode_DecodeFSDefault(info.pr_fname);
if (!py_name)
goto error;
/* SunOS truncates arguments to length PRARGSZ, very likely args are truncated.
* The only way to retrieve full command line is to parse process memory */
if (info.pr_argc && strlen(info.pr_psargs) == PRARGSZ-1) {
argv = psutil_read_raw_args(info, procfs_path, &argc);
if (argv) {
joined = cstrings_array_to_string(&argv_plain, argv, argc, ' ');
if (joined > 0) {
py_args = PyUnicode_DecodeFSDefault(argv_plain);
free(argv_plain);
} else if (joined < 0) {
goto error;
}
psutil_free_cstrings_array(argv, argc);
}
}
/* If we can't read process memory or can't decode the result
* then return args from /proc. */
if (!py_args) {
PyErr_Clear();
py_args = PyUnicode_DecodeFSDefault(info.pr_psargs);
}
/* Both methods has been failed. */
if (!py_args)
goto error;
py_retlist = Py_BuildValue("OO", py_name, py_args);
if (!py_retlist)
goto error;
Py_DECREF(py_name);
Py_DECREF(py_args);
return py_retlist;
error:
Py_XDECREF(py_name);
Py_XDECREF(py_args);
Py_XDECREF(py_retlist);
return NULL;
}
/*
* Return process environ block.
*/
static PyObject *
psutil_proc_environ(PyObject *self, PyObject *args) {
int pid;
char path[1000];
psinfo_t info;
const char *procfs_path;
char **env = NULL;
ssize_t env_count = -1;
char *dm;
int i = 0;
PyObject *py_envname = NULL;
PyObject *py_envval = NULL;
PyObject *py_retdict = PyDict_New();
if (! py_retdict)
return PyErr_NoMemory();
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/psinfo", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
goto error;
if (! info.pr_envp) {
AccessDenied("/proc/pid/psinfo struct not set");
goto error;
}
env = psutil_read_raw_env(info, procfs_path, &env_count);
if (! env && env_count != 0)
goto error;
for (i=0; i<env_count; i++) {
if (! env[i])
break;
dm = strchr(env[i], '=');
if (! dm)
continue;
*dm = '\0';
py_envname = PyUnicode_DecodeFSDefault(env[i]);
if (! py_envname)
goto error;
py_envval = PyUnicode_DecodeFSDefault(dm+1);
if (! py_envname)
goto error;
if (PyDict_SetItem(py_retdict, py_envname, py_envval) < 0)
goto error;
Py_CLEAR(py_envname);
Py_CLEAR(py_envval);
}
psutil_free_cstrings_array(env, env_count);
return py_retdict;
error:
if (env && env_count >= 0)
psutil_free_cstrings_array(env, env_count);
Py_XDECREF(py_envname);
Py_XDECREF(py_envval);
Py_XDECREF(py_retdict);
return NULL;
}
/*
* Return process user and system CPU times as a Python tuple.
*/
static PyObject *
psutil_proc_cpu_times(PyObject *self, PyObject *args) {
int pid;
char path[1000];
pstatus_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/status", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
// results are more precise than os.times()
return Py_BuildValue(
"(dddd)",
PSUTIL_TV2DOUBLE(info.pr_utime),
PSUTIL_TV2DOUBLE(info.pr_stime),
PSUTIL_TV2DOUBLE(info.pr_cutime),
PSUTIL_TV2DOUBLE(info.pr_cstime)
);
}
/*
* Return what CPU the process is running on.
*/
static PyObject *
psutil_proc_cpu_num(PyObject *self, PyObject *args) {
int fd = -1;
int pid;
char path[1000];
struct prheader header;
struct lwpsinfo *lwp = NULL;
int nent;
int size;
int proc_num;
ssize_t nbytes;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/lpsinfo", procfs_path, pid);
fd = open(path, O_RDONLY);
if (fd == -1) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
return NULL;
}
// read header
nbytes = pread(fd, &header, sizeof(header), 0);
if (nbytes == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if (nbytes != sizeof(header)) {
PyErr_SetString(
PyExc_RuntimeError, "read() file structure size mismatch");
goto error;
}
// malloc
nent = header.pr_nent;
size = header.pr_entsize * nent;
lwp = malloc(size);
if (lwp == NULL) {
PyErr_NoMemory();
goto error;
}
// read the rest
nbytes = pread(fd, lwp, size, sizeof(header));
if (nbytes == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if (nbytes != size) {
PyErr_SetString(
PyExc_RuntimeError, "read() file structure size mismatch");
goto error;
}
// done
proc_num = lwp->pr_onpro;
close(fd);
free(lwp);
return Py_BuildValue("i", proc_num);
error:
if (fd != -1)
close(fd);
free(lwp);
return NULL;
}
/*
* Return process uids/gids as a Python tuple.
*/
static PyObject *
psutil_proc_cred(PyObject *self, PyObject *args) {
int pid;
char path[1000];
prcred_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/cred", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
return Py_BuildValue("iiiiii",
info.pr_ruid, info.pr_euid, info.pr_suid,
info.pr_rgid, info.pr_egid, info.pr_sgid);
}
/*
* Return process voluntary and involuntary context switches as a Python tuple.
*/
static PyObject *
psutil_proc_num_ctx_switches(PyObject *self, PyObject *args) {
int pid;
char path[1000];
prusage_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/usage", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
return Py_BuildValue("kk", info.pr_vctx, info.pr_ictx);
}
/*
* Process IO counters.
*
* Commented out and left here as a reminder. Apparently we cannot
* retrieve process IO stats because:
* - 'pr_ioch' is a sum of chars read and written, with no distinction
* - 'pr_inblk' and 'pr_oublk', which should be the number of bytes
* read and written, hardly increase and according to:
* http://www.brendangregg.com/Solaris/paper_diskubyp1.pdf
* ...they should be meaningless anyway.
*
static PyObject*
proc_io_counters(PyObject* self, PyObject* args) {
int pid;
char path[1000];
prusage_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/usage", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
// On Solaris we only have 'pr_ioch' which accounts for bytes read
// *and* written.
// 'pr_inblk' and 'pr_oublk' should be expressed in blocks of
// 8KB according to:
// http://www.brendangregg.com/Solaris/paper_diskubyp1.pdf (pag. 8)
return Py_BuildValue("kkkk",
info.pr_ioch,
info.pr_ioch,
info.pr_inblk,
info.pr_oublk);
}
*/
/*
* Return information about a given process thread.
*/
static PyObject *
psutil_proc_query_thread(PyObject *self, PyObject *args) {
int pid, tid;
char path[1000];
lwpstatus_t info;
const char *procfs_path;
if (! PyArg_ParseTuple(args, "iis", &pid, &tid, &procfs_path))
return NULL;
sprintf(path, "%s/%i/lwp/%i/lwpstatus", procfs_path, pid, tid);
if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
return NULL;
return Py_BuildValue("dd",
PSUTIL_TV2DOUBLE(info.pr_utime),
PSUTIL_TV2DOUBLE(info.pr_stime));
}
/*
* Return information about system virtual memory.
*/
static PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
// XXX (arghhh!)
// total/free swap mem: commented out as for some reason I can't
// manage to get the same results shown by "swap -l", despite the
// code below is exactly the same as:
// http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/
// cmd/swap/swap.c
// We're going to parse "swap -l" output from Python (sigh!)
/*
struct swaptable *st;
struct swapent *swapent;
int i;
struct stat64 statbuf;
char *path;
char fullpath[MAXPATHLEN+1];
int num;
if ((num = swapctl(SC_GETNSWP, NULL)) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (num == 0) {
PyErr_SetString(PyExc_RuntimeError, "no swap devices configured");
return NULL;
}
if ((st = malloc(num * sizeof(swapent_t) + sizeof (int))) == NULL) {
PyErr_SetString(PyExc_RuntimeError, "malloc failed");
return NULL;
}
if ((path = malloc(num * MAXPATHLEN)) == NULL) {
PyErr_SetString(PyExc_RuntimeError, "malloc failed");
return NULL;
}
swapent = st->swt_ent;
for (i = 0; i < num; i++, swapent++) {
swapent->ste_path = path;
path += MAXPATHLEN;
}
st->swt_n = num;
if ((num = swapctl(SC_LIST, st)) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
swapent = st->swt_ent;
long t = 0, f = 0;
for (i = 0; i < num; i++, swapent++) {
int diskblks_per_page =(int)(sysconf(_SC_PAGESIZE) >> DEV_BSHIFT);
t += (long)swapent->ste_pages;
f += (long)swapent->ste_free;
}
free(st);
return Py_BuildValue("(kk)", t, f);
*/
kstat_ctl_t *kc;
kstat_t *k;
cpu_stat_t *cpu;
int cpu_count = 0;
int flag = 0;
uint_t sin = 0;
uint_t sout = 0;
kc = kstat_open();
if (kc == NULL)
return PyErr_SetFromErrno(PyExc_OSError);;
k = kc->kc_chain;
while (k != NULL) {
if ((strncmp(k->ks_name, "cpu_stat", 8) == 0) && \
(kstat_read(kc, k, NULL) != -1) )
{
flag = 1;
cpu = (cpu_stat_t *) k->ks_data;
sin += cpu->cpu_vminfo.pgswapin; // num pages swapped in
sout += cpu->cpu_vminfo.pgswapout; // num pages swapped out
}
cpu_count += 1;
k = k->ks_next;
}
kstat_close(kc);
if (!flag) {
PyErr_SetString(PyExc_RuntimeError, "no swap device was found");
return NULL;
}
return Py_BuildValue("(II)", sin, sout);
}
/*
* Return users currently connected on the system.
*/
static PyObject *
psutil_users(PyObject *self, PyObject *args) {
struct utmpx *ut;
PyObject *py_tuple = NULL;
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_user_proc = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
setutxent();
while (NULL != (ut = getutxent())) {
if (ut->ut_type == USER_PROCESS)
py_user_proc = Py_True;
else
py_user_proc = Py_False;
py_username = PyUnicode_DecodeFSDefault(ut->ut_user);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(ut->ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(ut->ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"(OOOdOi)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)ut->ut_tv.tv_sec, // tstamp
py_user_proc, // (bool) user process
ut->ut_pid // process id
);
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
}
endutxent();
return py_retlist;
error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
endutxent();
return NULL;
}
/*
* Return disk mounted partitions as a list of tuples including device,
* mount point and filesystem type.
*/
static PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
FILE *file;
struct mnttab mt;
PyObject *py_dev = NULL;
PyObject *py_mountp = NULL;
PyObject *py_tuple = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
file = fopen(MNTTAB, "rb");
if (file == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
while (getmntent(file, &mt) == 0) {
py_dev = PyUnicode_DecodeFSDefault(mt.mnt_special);
if (! py_dev)
goto error;
py_mountp = PyUnicode_DecodeFSDefault(mt.mnt_mountp);
if (! py_mountp)
goto error;
py_tuple = Py_BuildValue(
"(OOss)",
py_dev, // device
py_mountp, // mount point
mt.mnt_fstype, // fs type
mt.mnt_mntopts); // options
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_dev);
Py_CLEAR(py_mountp);
Py_CLEAR(py_tuple);
}
fclose(file);
return py_retlist;
error:
Py_XDECREF(py_dev);
Py_XDECREF(py_mountp);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (file != NULL)
fclose(file);
return NULL;
}
/*
* Return system-wide CPU times.
*/
static PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
kstat_ctl_t *kc;
kstat_t *ksp;
cpu_stat_t cs;
PyObject *py_retlist = PyList_New(0);
PyObject *py_cputime = NULL;
if (py_retlist == NULL)
return NULL;
kc = kstat_open();
if (kc == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
if (strcmp(ksp->ks_module, "cpu_stat") == 0) {
if (kstat_read(kc, ksp, &cs) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
py_cputime = Py_BuildValue("ffff",
(float)cs.cpu_sysinfo.cpu[CPU_USER],
(float)cs.cpu_sysinfo.cpu[CPU_KERNEL],
(float)cs.cpu_sysinfo.cpu[CPU_IDLE],
(float)cs.cpu_sysinfo.cpu[CPU_WAIT]);
if (py_cputime == NULL)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_CLEAR(py_cputime);
}
}
kstat_close(kc);
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
if (kc != NULL)
kstat_close(kc);
return NULL;
}
/*
* Return disk IO statistics.
*/
static PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
kstat_ctl_t *kc;
kstat_t *ksp;
kstat_io_t kio;
PyObject *py_retdict = PyDict_New();
PyObject *py_disk_info = NULL;
if (py_retdict == NULL)
return NULL;
kc = kstat_open();
if (kc == NULL) {
PyErr_SetFromErrno(PyExc_OSError);;
goto error;
}
ksp = kc->kc_chain;
while (ksp != NULL) {
if (ksp->ks_type == KSTAT_TYPE_IO) {
if (strcmp(ksp->ks_class, "disk") == 0) {
if (kstat_read(kc, ksp, &kio) == -1) {
kstat_close(kc);
return PyErr_SetFromErrno(PyExc_OSError);;
}
py_disk_info = Py_BuildValue(
"(IIKKLL)",
kio.reads,
kio.writes,
kio.nread,
kio.nwritten,
kio.rtime / 1000 / 1000, // from nano to milli secs
kio.wtime / 1000 / 1000 // from nano to milli secs
);
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, ksp->ks_name,
py_disk_info))
goto error;
Py_CLEAR(py_disk_info);
}
}
ksp = ksp->ks_next;
}
kstat_close(kc);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (kc != NULL)
kstat_close(kc);
return NULL;
}
/*
* Return process memory mappings.
*/
static PyObject *
psutil_proc_memory_maps(PyObject *self, PyObject *args) {
int pid;
int fd = -1;
char path[1000];
char perms[10];
const char *name;
struct stat st;
pstatus_t status;
prxmap_t *xmap = NULL, *p;
off_t size;
size_t nread;
int nmap;
uintptr_t pr_addr_sz;
uintptr_t stk_base_sz, brk_base_sz;
const char *procfs_path;
PyObject *py_tuple = NULL;
PyObject *py_path = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
goto error;
sprintf(path, "%s/%i/status", procfs_path, pid);
if (! psutil_file_to_struct(path, (void *)&status, sizeof(status)))
goto error;
sprintf(path, "%s/%i/xmap", procfs_path, pid);
if (stat(path, &st) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
size = st.st_size;
fd = open(path, O_RDONLY);
if (fd == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
xmap = (prxmap_t *)malloc(size);
if (xmap == NULL) {
PyErr_NoMemory();
goto error;
}
nread = pread(fd, xmap, size, 0);
nmap = nread / sizeof(prxmap_t);
p = xmap;
while (nmap) {
nmap -= 1;
if (p == NULL) {
p += 1;
continue;
}
perms[0] = '\0';
pr_addr_sz = p->pr_vaddr + p->pr_size;
// perms
sprintf(perms, "%c%c%c%c", p->pr_mflags & MA_READ ? 'r' : '-',
p->pr_mflags & MA_WRITE ? 'w' : '-',
p->pr_mflags & MA_EXEC ? 'x' : '-',
p->pr_mflags & MA_SHARED ? 's' : '-');
// name
if (strlen(p->pr_mapname) > 0) {
name = p->pr_mapname;
}
else {
if ((p->pr_mflags & MA_ISM) || (p->pr_mflags & MA_SHM)) {
name = "[shmid]";
}
else {
stk_base_sz = status.pr_stkbase + status.pr_stksize;
brk_base_sz = status.pr_brkbase + status.pr_brksize;
if ((pr_addr_sz > status.pr_stkbase) &&
(p->pr_vaddr < stk_base_sz)) {
name = "[stack]";
}
else if ((p->pr_mflags & MA_ANON) && \
(pr_addr_sz > status.pr_brkbase) && \
(p->pr_vaddr < brk_base_sz)) {
name = "[heap]";
}
else {
name = "[anon]";
}
}
}
py_path = PyUnicode_DecodeFSDefault(name);
if (! py_path)
goto error;
py_tuple = Py_BuildValue(
"kksOkkk",
(unsigned long)p->pr_vaddr,
(unsigned long)pr_addr_sz,
perms,
py_path,
(unsigned long)p->pr_rss * p->pr_pagesize,
(unsigned long)p->pr_anon * p->pr_pagesize,
(unsigned long)p->pr_locked * p->pr_pagesize);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_path);
Py_CLEAR(py_tuple);
// increment pointer
p += 1;
}
close(fd);
free(xmap);
return py_retlist;
error:
if (fd != -1)
close(fd);
Py_XDECREF(py_tuple);
Py_XDECREF(py_path);
Py_DECREF(py_retlist);
if (xmap != NULL)
free(xmap);
return NULL;
}
/*
* Return a list of tuples for network I/O statistics.
*/
static PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args) {
kstat_ctl_t *kc = NULL;
kstat_t *ksp;
kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs;
int ret;
int sock = -1;
struct lifreq ifr;
PyObject *py_retdict = PyDict_New();
PyObject *py_ifc_info = NULL;
if (py_retdict == NULL)
return NULL;
kc = kstat_open();
if (kc == NULL)
goto error;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
ksp = kc->kc_chain;
while (ksp != NULL) {
if (ksp->ks_type != KSTAT_TYPE_NAMED)
goto next;
if (strcmp(ksp->ks_class, "net") != 0)
goto next;
// skip 'lo' (localhost) because it doesn't have the statistics we need
// and it makes kstat_data_lookup() fail
if (strcmp(ksp->ks_module, "lo") == 0)
goto next;
// check if this is a network interface by sending a ioctl
PSUTIL_STRNCPY(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name));
ret = ioctl(sock, SIOCGLIFFLAGS, &ifr);
if (ret == -1)
goto next;
if (kstat_read(kc, ksp, NULL) == -1) {
errno = 0;
goto next;
}
rbytes = (kstat_named_t *)kstat_data_lookup(ksp, "rbytes");
wbytes = (kstat_named_t *)kstat_data_lookup(ksp, "obytes");
rpkts = (kstat_named_t *)kstat_data_lookup(ksp, "ipackets");
wpkts = (kstat_named_t *)kstat_data_lookup(ksp, "opackets");
ierrs = (kstat_named_t *)kstat_data_lookup(ksp, "ierrors");
oerrs = (kstat_named_t *)kstat_data_lookup(ksp, "oerrors");
if ((rbytes == NULL) || (wbytes == NULL) || (rpkts == NULL) ||
(wpkts == NULL) || (ierrs == NULL) || (oerrs == NULL))
{
PyErr_SetString(PyExc_RuntimeError, "kstat_data_lookup() failed");
goto error;
}
if (rbytes->data_type == KSTAT_DATA_UINT64)
{
py_ifc_info = Py_BuildValue("(KKKKIIii)",
wbytes->value.ui64,
rbytes->value.ui64,
wpkts->value.ui64,
rpkts->value.ui64,
ierrs->value.ui32,
oerrs->value.ui32,
0, // dropin not supported
0 // dropout not supported
);
}
else
{
py_ifc_info = Py_BuildValue("(IIIIIIii)",
wbytes->value.ui32,
rbytes->value.ui32,
wpkts->value.ui32,
rpkts->value.ui32,
ierrs->value.ui32,
oerrs->value.ui32,
0, // dropin not supported
0 // dropout not supported
);
}
if (!py_ifc_info)
goto error;
if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
goto error;
Py_CLEAR(py_ifc_info);
goto next;
next:
ksp = ksp->ks_next;
}
kstat_close(kc);
close(sock);
return py_retdict;
error:
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (kc != NULL)
kstat_close(kc);
if (sock != -1) {
close(sock);
}
return NULL;
}
/*
* Return TCP and UDP connections opened by process.
* UNIX sockets are excluded.
*
* Thanks to:
* https://github.com/DavidGriffith/finx/blob/master/
* nxsensor-3.5.0-1/src/sysdeps/solaris.c
* ...and:
* https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/
* cmd-inet/usr.bin/netstat/netstat.c
*/
static PyObject *
psutil_net_connections(PyObject *self, PyObject *args) {
long pid;
int sd = 0;
mib2_tcpConnEntry_t tp;
mib2_udpEntry_t ude;
#if defined(AF_INET6)
mib2_tcp6ConnEntry_t tp6;
mib2_udp6Entry_t ude6;
#endif
char buf[512];
int i, flags, getcode, num_ent, state, ret;
char lip[INET6_ADDRSTRLEN], rip[INET6_ADDRSTRLEN];
int lport, rport;
int processed_pid;
int databuf_init = 0;
struct strbuf ctlbuf, databuf;
struct T_optmgmt_req tor = {0};
struct T_optmgmt_ack toa = {0};
struct T_error_ack tea = {0};
struct opthdr mibhdr = {0};
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "l", &pid))
goto error;
sd = open("/dev/arp", O_RDWR);
if (sd == -1) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp");
goto error;
}
ret = ioctl(sd, I_PUSH, "tcp");
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
ret = ioctl(sd, I_PUSH, "udp");
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
//
// OK, this mess is basically copied and pasted from nxsensor project
// which copied and pasted it from netstat source code, mibget()
// function. Also see:
// http://stackoverflow.com/questions/8723598/
tor.PRIM_type = T_SVR4_OPTMGMT_REQ;
tor.OPT_offset = sizeof (struct T_optmgmt_req);
tor.OPT_length = sizeof (struct opthdr);
tor.MGMT_flags = T_CURRENT;
mibhdr.level = MIB2_IP;
mibhdr.name = 0;
#ifdef NEW_MIB_COMPLIANT
mibhdr.len = 1;
#else
mibhdr.len = 0;
#endif
memcpy(buf, &tor, sizeof tor);
memcpy(buf + tor.OPT_offset, &mibhdr, sizeof mibhdr);
ctlbuf.buf = buf;
ctlbuf.len = tor.OPT_offset + tor.OPT_length;
flags = 0; // request to be sent in non-priority
if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
ctlbuf.maxlen = sizeof (buf);
for (;;) {
flags = 0;
getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);
memcpy(&toa, buf, sizeof toa);
memcpy(&tea, buf, sizeof tea);
if (getcode != MOREDATA ||
ctlbuf.len < (int)sizeof (struct T_optmgmt_ack) ||
toa.PRIM_type != T_OPTMGMT_ACK ||
toa.MGMT_flags != T_SUCCESS)
{
break;
}
if (ctlbuf.len >= (int)sizeof (struct T_error_ack) &&
tea.PRIM_type == T_ERROR_ACK)
{
PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK");
goto error;
}
if (getcode == 0 &&
ctlbuf.len >= (int)sizeof (struct T_optmgmt_ack) &&
toa.PRIM_type == T_OPTMGMT_ACK &&
toa.MGMT_flags == T_SUCCESS)
{
PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK");
goto error;
}
memset(&mibhdr, 0x0, sizeof(mibhdr));
memcpy(&mibhdr, buf + toa.OPT_offset, toa.OPT_length);
databuf.maxlen = mibhdr.len;
databuf.len = 0;
databuf.buf = (char *)malloc((int)mibhdr.len);
if (!databuf.buf) {
PyErr_NoMemory();
goto error;
}
databuf_init = 1;
flags = 0;
getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags);
if (getcode < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
// TCPv4
if (mibhdr.level == MIB2_TCP && mibhdr.name == MIB2_TCP_13) {
num_ent = mibhdr.len / sizeof(mib2_tcpConnEntry_t);
for (i = 0; i < num_ent; i++) {
memcpy(&tp, databuf.buf + i * sizeof tp, sizeof tp);
#ifdef NEW_MIB_COMPLIANT
processed_pid = tp.tcpConnCreationProcess;
#else
processed_pid = 0;
#endif
if (pid != -1 && processed_pid != pid)
continue;
// construct local/remote addresses
inet_ntop(AF_INET, &tp.tcpConnLocalAddress, lip, sizeof(lip));
inet_ntop(AF_INET, &tp.tcpConnRemAddress, rip, sizeof(rip));
lport = tp.tcpConnLocalPort;
rport = tp.tcpConnRemPort;
// construct python tuple/list
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", rip, rport);
else {
py_raddr = Py_BuildValue("()");
}
if (!py_raddr)
goto error;
state = tp.tcpConnEntryInfo.ce_state;
// add item
py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_STREAM,
py_laddr, py_raddr, state,
processed_pid);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
}
#if defined(AF_INET6)
// TCPv6
else if (mibhdr.level == MIB2_TCP6 && mibhdr.name == MIB2_TCP6_CONN)
{
num_ent = mibhdr.len / sizeof(mib2_tcp6ConnEntry_t);
for (i = 0; i < num_ent; i++) {
memcpy(&tp6, databuf.buf + i * sizeof tp6, sizeof tp6);
#ifdef NEW_MIB_COMPLIANT
processed_pid = tp6.tcp6ConnCreationProcess;
#else
processed_pid = 0;
#endif
if (pid != -1 && processed_pid != pid)
continue;
// construct local/remote addresses
inet_ntop(AF_INET6, &tp6.tcp6ConnLocalAddress, lip, sizeof(lip));
inet_ntop(AF_INET6, &tp6.tcp6ConnRemAddress, rip, sizeof(rip));
lport = tp6.tcp6ConnLocalPort;
rport = tp6.tcp6ConnRemPort;
// construct python tuple/list
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", rip, rport);
else
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
state = tp6.tcp6ConnEntryInfo.ce_state;
// add item
py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_STREAM,
py_laddr, py_raddr, state, processed_pid);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
}
#endif
// UDPv4
else if (mibhdr.level == MIB2_UDP || mibhdr.level == MIB2_UDP_ENTRY) {
num_ent = mibhdr.len / sizeof(mib2_udpEntry_t);
assert(num_ent * sizeof(mib2_udpEntry_t) == mibhdr.len);
for (i = 0; i < num_ent; i++) {
memcpy(&ude, databuf.buf + i * sizeof ude, sizeof ude);
#ifdef NEW_MIB_COMPLIANT
processed_pid = ude.udpCreationProcess;
#else
processed_pid = 0;
#endif
if (pid != -1 && processed_pid != pid)
continue;
// XXX Very ugly hack! It seems we get here only the first
// time we bump into a UDPv4 socket. PID is a very high
// number (clearly impossible) and the address does not
// belong to any valid interface. Not sure what else
// to do other than skipping.
if (processed_pid > 131072)
continue;
inet_ntop(AF_INET, &ude.udpLocalAddress, lip, sizeof(lip));
lport = ude.udpLocalPort;
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_DGRAM,
py_laddr, py_raddr, PSUTIL_CONN_NONE,
processed_pid);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
}
#if defined(AF_INET6)
// UDPv6
else if (mibhdr.level == MIB2_UDP6 ||
mibhdr.level == MIB2_UDP6_ENTRY)
{
num_ent = mibhdr.len / sizeof(mib2_udp6Entry_t);
for (i = 0; i < num_ent; i++) {
memcpy(&ude6, databuf.buf + i * sizeof ude6, sizeof ude6);
#ifdef NEW_MIB_COMPLIANT
processed_pid = ude6.udp6CreationProcess;
#else
processed_pid = 0;
#endif
if (pid != -1 && processed_pid != pid)
continue;
inet_ntop(AF_INET6, &ude6.udp6LocalAddress, lip, sizeof(lip));
lport = ude6.udp6LocalPort;
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM,
py_laddr, py_raddr, PSUTIL_CONN_NONE,
processed_pid);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
}
#endif
free(databuf.buf);
}
close(sd);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
Py_DECREF(py_retlist);
if (databuf_init == 1)
free(databuf.buf);
if (sd != 0)
close(sd);
return NULL;
}
static PyObject *
psutil_boot_time(PyObject *self, PyObject *args) {
float boot_time = 0.0;
struct utmpx *ut;
setutxent();
while (NULL != (ut = getutxent())) {
if (ut->ut_type == BOOT_TIME) {
boot_time = (float)ut->ut_tv.tv_sec;
break;
}
}
endutxent();
if (fabs(boot_time) < 0.000001) {
/* could not find BOOT_TIME in getutxent loop */
PyErr_SetString(PyExc_RuntimeError, "can't determine boot time");
return NULL;
}
return Py_BuildValue("f", boot_time);
}
/*
* Return the number of CPU cores on the system.
*/
static PyObject *
psutil_cpu_count_cores(PyObject *self, PyObject *args) {
kstat_ctl_t *kc;
kstat_t *ksp;
int ncpus = 0;
kc = kstat_open();
if (kc == NULL)
goto error;
ksp = kstat_lookup(kc, "cpu_info", -1, NULL);
if (ksp == NULL)
goto error;
for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) {
if (strcmp(ksp->ks_module, "cpu_info") != 0)
continue;
if (kstat_read(kc, ksp, NULL) == -1)
goto error;
ncpus += 1;
}
kstat_close(kc);
if (ncpus > 0)
return Py_BuildValue("i", ncpus);
else
goto error;
error:
// mimic os.cpu_count()
if (kc != NULL)
kstat_close(kc);
Py_RETURN_NONE;
}
/*
* Return stats about a particular network
* interface. References:
* https://github.com/dpaleino/wicd/blob/master/wicd/backends/be-ioctl.py
* http://www.i-scream.org/libstatgrab/
*/
static PyObject*
psutil_net_if_stats(PyObject* self, PyObject* args) {
kstat_ctl_t *kc = NULL;
kstat_t *ksp;
kstat_named_t *knp;
int ret;
int sock = -1;
int duplex;
int speed;
PyObject *py_retdict = PyDict_New();
PyObject *py_ifc_info = NULL;
PyObject *py_is_up = NULL;
if (py_retdict == NULL)
return NULL;
kc = kstat_open();
if (kc == NULL)
goto error;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) {
if (strcmp(ksp->ks_class, "net") == 0) {
struct lifreq ifr;
kstat_read(kc, ksp, NULL);
if (ksp->ks_type != KSTAT_TYPE_NAMED)
continue;
if (strcmp(ksp->ks_class, "net") != 0)
continue;
PSUTIL_STRNCPY(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name));
ret = ioctl(sock, SIOCGLIFFLAGS, &ifr);
if (ret == -1)
continue; // not a network interface
// is up?
if ((ifr.lifr_flags & IFF_UP) != 0) {
if ((knp = kstat_data_lookup(ksp, "link_up")) != NULL) {
if (knp->value.ui32 != 0u)
py_is_up = Py_True;
else
py_is_up = Py_False;
}
else {
py_is_up = Py_True;
}
}
else {
py_is_up = Py_False;
}
Py_INCREF(py_is_up);
// duplex
duplex = 0; // unknown
if ((knp = kstat_data_lookup(ksp, "link_duplex")) != NULL) {
if (knp->value.ui32 == 1)
duplex = 1; // half
else if (knp->value.ui32 == 2)
duplex = 2; // full
}
// speed
if ((knp = kstat_data_lookup(ksp, "ifspeed")) != NULL)
// expressed in bits per sec, we want mega bits per sec
speed = (int)knp->value.ui64 / 1000000;
else
speed = 0;
// mtu
ret = ioctl(sock, SIOCGLIFMTU, &ifr);
if (ret == -1)
goto error;
py_ifc_info = Py_BuildValue("(Oiii)", py_is_up, duplex, speed,
ifr.lifr_mtu);
if (!py_ifc_info)
goto error;
if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
goto error;
Py_CLEAR(py_ifc_info);
}
}
close(sock);
kstat_close(kc);
return py_retdict;
error:
Py_XDECREF(py_is_up);
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (sock != -1)
close(sock);
if (kc != NULL)
kstat_close(kc);
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/*
* Return CPU statistics.
*/
static PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
kstat_ctl_t *kc;
kstat_t *ksp;
cpu_stat_t cs;
unsigned int ctx_switches = 0;
unsigned int interrupts = 0;
unsigned int traps = 0;
unsigned int syscalls = 0;
kc = kstat_open();
if (kc == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
if (strcmp(ksp->ks_module, "cpu_stat") == 0) {
if (kstat_read(kc, ksp, &cs) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
// voluntary + involuntary
ctx_switches += cs.cpu_sysinfo.pswitch + cs.cpu_sysinfo.inv_swtch;
interrupts += cs.cpu_sysinfo.intr;
traps += cs.cpu_sysinfo.trap;
syscalls += cs.cpu_sysinfo.syscall;
}
}
kstat_close(kc);
return Py_BuildValue(
"IIII", ctx_switches, interrupts, syscalls, traps);
error:
if (kc != NULL)
kstat_close(kc);
return NULL;
}
/*
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef
PsutilMethods[] = {
// --- process-related functions
{"proc_basic_info", psutil_proc_basic_info, METH_VARARGS},
{"proc_cpu_num", psutil_proc_cpu_num, METH_VARARGS},
{"proc_cpu_times", psutil_proc_cpu_times, METH_VARARGS},
{"proc_cred", psutil_proc_cred, METH_VARARGS},
{"proc_environ", psutil_proc_environ, METH_VARARGS},
{"proc_memory_maps", psutil_proc_memory_maps, METH_VARARGS},
{"proc_name_and_args", psutil_proc_name_and_args, METH_VARARGS},
{"proc_num_ctx_switches", psutil_proc_num_ctx_switches, METH_VARARGS},
{"query_process_thread", psutil_proc_query_thread, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"cpu_count_cores", psutil_cpu_count_cores, METH_VARARGS},
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"net_connections", psutil_net_connections, METH_VARARGS},
{"net_if_stats", psutil_net_if_stats, METH_VARARGS},
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"swap_mem", psutil_swap_mem, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
struct module_state {
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
#endif
#if PY_MAJOR_VERSION >= 3
static int
psutil_sunos_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(GETSTATE(m)->error);
return 0;
}
static int
psutil_sunos_clear(PyObject *m) {
Py_CLEAR(GETSTATE(m)->error);
return 0;
}
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"psutil_sunos",
NULL,
sizeof(struct module_state),
PsutilMethods,
NULL,
psutil_sunos_traverse,
psutil_sunos_clear,
NULL
};
#define INITERROR return NULL
PyMODINIT_FUNC PyInit__psutil_sunos(void)
#else
#define INITERROR return
void init_psutil_sunos(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule("_psutil_sunos", PsutilMethods);
#endif
if (module == NULL)
INITERROR;
if (psutil_setup() != 0)
INITERROR;
PyModule_AddIntConstant(module, "version", PSUTIL_VERSION);
PyModule_AddIntConstant(module, "SSLEEP", SSLEEP);
PyModule_AddIntConstant(module, "SRUN", SRUN);
PyModule_AddIntConstant(module, "SZOMB", SZOMB);
PyModule_AddIntConstant(module, "SSTOP", SSTOP);
PyModule_AddIntConstant(module, "SIDL", SIDL);
PyModule_AddIntConstant(module, "SONPROC", SONPROC);
#ifdef SWAIT
PyModule_AddIntConstant(module, "SWAIT", SWAIT);
#else
/* sys/proc.h started defining SWAIT somewhere
* after Update 3 and prior to Update 5 included.
*/
PyModule_AddIntConstant(module, "SWAIT", 0);
#endif
PyModule_AddIntConstant(module, "PRNODEV", PRNODEV); // for process tty
PyModule_AddIntConstant(module, "TCPS_CLOSED", TCPS_CLOSED);
PyModule_AddIntConstant(module, "TCPS_CLOSING", TCPS_CLOSING);
PyModule_AddIntConstant(module, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT);
PyModule_AddIntConstant(module, "TCPS_LISTEN", TCPS_LISTEN);
PyModule_AddIntConstant(module, "TCPS_ESTABLISHED", TCPS_ESTABLISHED);
PyModule_AddIntConstant(module, "TCPS_SYN_SENT", TCPS_SYN_SENT);
PyModule_AddIntConstant(module, "TCPS_SYN_RCVD", TCPS_SYN_RCVD);
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1);
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2);
PyModule_AddIntConstant(module, "TCPS_LAST_ACK", TCPS_LAST_ACK);
PyModule_AddIntConstant(module, "TCPS_TIME_WAIT", TCPS_TIME_WAIT);
// sunos specific
PyModule_AddIntConstant(module, "TCPS_IDLE", TCPS_IDLE);
// sunos specific
PyModule_AddIntConstant(module, "TCPS_BOUND", TCPS_BOUND);
PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
if (module == NULL)
INITERROR;
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
| 50,462 | 27.542421 | 83 | c |
psutil | psutil-master/psutil/_psutil_windows.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Windows platform-specific module methods for _psutil_windows.
*
* List of undocumented Windows NT APIs which are used in here and in
* other modules:
* - NtQuerySystemInformation
* - NtQueryInformationProcess
* - NtQueryObject
* - NtSuspendProcess
* - NtResumeProcess
*/
#include <Python.h>
#include <windows.h>
#include "_psutil_common.h"
#include "arch/windows/cpu.h"
#include "arch/windows/disk.h"
#include "arch/windows/mem.h"
#include "arch/windows/net.h"
#include "arch/windows/proc.h"
#include "arch/windows/proc_handles.h"
#include "arch/windows/proc_info.h"
#include "arch/windows/proc_utils.h"
#include "arch/windows/security.h"
#include "arch/windows/sensors.h"
#include "arch/windows/services.h"
#include "arch/windows/socks.h"
#include "arch/windows/sys.h"
#include "arch/windows/wmi.h"
// ------------------------ Python init ---------------------------
static PyMethodDef
PsutilMethods[] = {
// --- per-process functions
{"proc_cmdline", (PyCFunction)(void(*)(void))psutil_proc_cmdline,
METH_VARARGS | METH_KEYWORDS},
{"proc_cpu_affinity_get", psutil_proc_cpu_affinity_get, METH_VARARGS},
{"proc_cpu_affinity_set", psutil_proc_cpu_affinity_set, METH_VARARGS},
{"proc_cwd", psutil_proc_cwd, METH_VARARGS},
{"proc_environ", psutil_proc_environ, METH_VARARGS},
{"proc_exe", psutil_proc_exe, METH_VARARGS},
{"proc_io_counters", psutil_proc_io_counters, METH_VARARGS},
{"proc_io_priority_get", psutil_proc_io_priority_get, METH_VARARGS},
{"proc_io_priority_set", psutil_proc_io_priority_set, METH_VARARGS},
{"proc_is_suspended", psutil_proc_is_suspended, METH_VARARGS},
{"proc_kill", psutil_proc_kill, METH_VARARGS},
{"proc_memory_info", psutil_proc_memory_info, METH_VARARGS},
{"proc_memory_maps", psutil_proc_memory_maps, METH_VARARGS},
{"proc_memory_uss", psutil_proc_memory_uss, METH_VARARGS},
{"proc_num_handles", psutil_proc_num_handles, METH_VARARGS},
{"proc_open_files", psutil_proc_open_files, METH_VARARGS},
{"proc_priority_get", psutil_proc_priority_get, METH_VARARGS},
{"proc_priority_set", psutil_proc_priority_set, METH_VARARGS},
{"proc_suspend_or_resume", psutil_proc_suspend_or_resume, METH_VARARGS},
{"proc_threads", psutil_proc_threads, METH_VARARGS},
{"proc_times", psutil_proc_times, METH_VARARGS},
{"proc_username", psutil_proc_username, METH_VARARGS},
{"proc_wait", psutil_proc_wait, METH_VARARGS},
// --- alternative pinfo interface
{"proc_info", psutil_proc_info, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"cpu_count_cores", psutil_cpu_count_cores, METH_VARARGS},
{"cpu_count_logical", psutil_cpu_count_logical, METH_VARARGS},
{"cpu_freq", psutil_cpu_freq, METH_VARARGS},
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"cpu_times", psutil_cpu_times, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"disk_usage", psutil_disk_usage, METH_VARARGS},
{"getloadavg", (PyCFunction)psutil_get_loadavg, METH_VARARGS},
{"getpagesize", psutil_getpagesize, METH_VARARGS},
{"swap_percent", psutil_swap_percent, METH_VARARGS},
{"init_loadavg_counter", (PyCFunction)psutil_init_loadavg_counter, METH_VARARGS},
{"net_connections", psutil_net_connections, METH_VARARGS},
{"net_if_addrs", psutil_net_if_addrs, METH_VARARGS},
{"net_if_stats", psutil_net_if_stats, METH_VARARGS},
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"pid_exists", psutil_pid_exists, METH_VARARGS},
{"pids", psutil_pids, METH_VARARGS},
{"ppid_map", psutil_ppid_map, METH_VARARGS},
{"sensors_battery", psutil_sensors_battery, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"virtual_mem", psutil_virtual_mem, METH_VARARGS},
// --- windows services
{"winservice_enumerate", psutil_winservice_enumerate, METH_VARARGS},
{"winservice_query_config", psutil_winservice_query_config, METH_VARARGS},
{"winservice_query_descr", psutil_winservice_query_descr, METH_VARARGS},
{"winservice_query_status", psutil_winservice_query_status, METH_VARARGS},
{"winservice_start", psutil_winservice_start, METH_VARARGS},
{"winservice_stop", psutil_winservice_stop, METH_VARARGS},
// --- windows API bindings
{"QueryDosDevice", psutil_QueryDosDevice, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
struct module_state {
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif
#if PY_MAJOR_VERSION >= 3
static int psutil_windows_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(GETSTATE(m)->error);
return 0;
}
static int psutil_windows_clear(PyObject *m) {
Py_CLEAR(GETSTATE(m)->error);
return 0;
}
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"psutil_windows",
NULL,
sizeof(struct module_state),
PsutilMethods,
NULL,
psutil_windows_traverse,
psutil_windows_clear,
NULL
};
#define INITERROR return NULL
PyMODINIT_FUNC PyInit__psutil_windows(void)
#else
#define INITERROR return
void init_psutil_windows(void)
#endif
{
struct module_state *st = NULL;
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule("_psutil_windows", PsutilMethods);
#endif
if (module == NULL)
INITERROR;
if (psutil_setup() != 0)
INITERROR;
if (psutil_set_se_debug() != 0)
INITERROR;
st = GETSTATE(module);
st->error = PyErr_NewException("_psutil_windows.Error", NULL, NULL);
if (st->error == NULL) {
Py_DECREF(module);
INITERROR;
}
// Exceptions.
TimeoutExpired = PyErr_NewException(
"_psutil_windows.TimeoutExpired", NULL, NULL);
Py_INCREF(TimeoutExpired);
PyModule_AddObject(module, "TimeoutExpired", TimeoutExpired);
TimeoutAbandoned = PyErr_NewException(
"_psutil_windows.TimeoutAbandoned", NULL, NULL);
Py_INCREF(TimeoutAbandoned);
PyModule_AddObject(module, "TimeoutAbandoned", TimeoutAbandoned);
// version constant
PyModule_AddIntConstant(module, "version", PSUTIL_VERSION);
// process status constants
// http://msdn.microsoft.com/en-us/library/ms683211(v=vs.85).aspx
PyModule_AddIntConstant(
module, "ABOVE_NORMAL_PRIORITY_CLASS", ABOVE_NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "BELOW_NORMAL_PRIORITY_CLASS", BELOW_NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "HIGH_PRIORITY_CLASS", HIGH_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "IDLE_PRIORITY_CLASS", IDLE_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "NORMAL_PRIORITY_CLASS", NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "REALTIME_PRIORITY_CLASS", REALTIME_PRIORITY_CLASS);
// connection status constants
// http://msdn.microsoft.com/en-us/library/cc669305.aspx
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_CLOSED", MIB_TCP_STATE_CLOSED);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_CLOSING", MIB_TCP_STATE_CLOSING);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_CLOSE_WAIT", MIB_TCP_STATE_CLOSE_WAIT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_LISTEN", MIB_TCP_STATE_LISTEN);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_ESTAB", MIB_TCP_STATE_ESTAB);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_SYN_SENT", MIB_TCP_STATE_SYN_SENT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_SYN_RCVD", MIB_TCP_STATE_SYN_RCVD);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_FIN_WAIT1", MIB_TCP_STATE_FIN_WAIT1);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_FIN_WAIT2", MIB_TCP_STATE_FIN_WAIT2);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_LAST_ACK", MIB_TCP_STATE_LAST_ACK);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_DELETE_TCB", MIB_TCP_STATE_DELETE_TCB);
PyModule_AddIntConstant(
module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
// service status constants
/*
PyModule_AddIntConstant(
module, "SERVICE_CONTINUE_PENDING", SERVICE_CONTINUE_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_PAUSE_PENDING", SERVICE_PAUSE_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_PAUSED", SERVICE_PAUSED);
PyModule_AddIntConstant(
module, "SERVICE_RUNNING", SERVICE_RUNNING);
PyModule_AddIntConstant(
module, "SERVICE_START_PENDING", SERVICE_START_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_STOP_PENDING", SERVICE_STOP_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_STOPPED", SERVICE_STOPPED);
*/
// ...for internal use in _psutil_windows.py
PyModule_AddIntConstant(
module, "INFINITE", INFINITE);
PyModule_AddIntConstant(
module, "ERROR_ACCESS_DENIED", ERROR_ACCESS_DENIED);
PyModule_AddIntConstant(
module, "ERROR_INVALID_NAME", ERROR_INVALID_NAME);
PyModule_AddIntConstant(
module, "ERROR_SERVICE_DOES_NOT_EXIST", ERROR_SERVICE_DOES_NOT_EXIST);
PyModule_AddIntConstant(
module, "ERROR_PRIVILEGE_NOT_HELD", ERROR_PRIVILEGE_NOT_HELD);
PyModule_AddIntConstant(
module, "WINVER", PSUTIL_WINVER);
PyModule_AddIntConstant(
module, "WINDOWS_VISTA", PSUTIL_WINDOWS_VISTA);
PyModule_AddIntConstant(
module, "WINDOWS_7", PSUTIL_WINDOWS_7);
PyModule_AddIntConstant(
module, "WINDOWS_8", PSUTIL_WINDOWS_8);
PyModule_AddIntConstant(
module, "WINDOWS_8_1", PSUTIL_WINDOWS_8_1);
PyModule_AddIntConstant(
module, "WINDOWS_10", PSUTIL_WINDOWS_10);
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
| 10,563 | 35.937063 | 85 | c |
psutil | psutil-master/psutil/_pswindows.py | # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Windows platform implementation."""
import contextlib
import errno
import functools
import os
import signal
import sys
import time
from collections import namedtuple
from . import _common
from ._common import ENCODING
from ._common import ENCODING_ERRS
from ._common import AccessDenied
from ._common import NoSuchProcess
from ._common import TimeoutExpired
from ._common import conn_tmap
from ._common import conn_to_ntuple
from ._common import debug
from ._common import isfile_strict
from ._common import memoize
from ._common import memoize_when_activated
from ._common import parse_environ_block
from ._common import usage_percent
from ._compat import PY3
from ._compat import long
from ._compat import lru_cache
from ._compat import range
from ._compat import unicode
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS
from ._psutil_windows import HIGH_PRIORITY_CLASS
from ._psutil_windows import IDLE_PRIORITY_CLASS
from ._psutil_windows import NORMAL_PRIORITY_CLASS
from ._psutil_windows import REALTIME_PRIORITY_CLASS
try:
from . import _psutil_windows as cext
except ImportError as err:
if str(err).lower().startswith("dll load failed") and \
sys.getwindowsversion()[0] < 6:
# We may get here if:
# 1) we are on an old Windows version
# 2) psutil was installed via pip + wheel
# See: https://github.com/giampaolo/psutil/issues/811
msg = "this Windows version is too old (< Windows Vista); "
msg += "psutil 3.4.2 is the latest version which supports Windows "
msg += "2000, XP and 2003 server"
raise RuntimeError(msg)
else:
raise
if sys.version_info >= (3, 4):
import enum
else:
enum = None
# process priority constants, import from __init__.py:
# http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
__extra__all__ = [
"win_service_iter", "win_service_get",
# Process priority
"ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
"HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", "NORMAL_PRIORITY_CLASS",
"REALTIME_PRIORITY_CLASS",
# IO priority
"IOPRIO_VERYLOW", "IOPRIO_LOW", "IOPRIO_NORMAL", "IOPRIO_HIGH",
# others
"CONN_DELETE_TCB", "AF_LINK",
]
# =====================================================================
# --- globals
# =====================================================================
CONN_DELETE_TCB = "DELETE_TCB"
ERROR_PARTIAL_COPY = 299
PYPY = '__pypy__' in sys.builtin_module_names
if enum is None:
AF_LINK = -1
else:
AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1})
AF_LINK = AddressFamily.AF_LINK
TCP_STATUSES = {
cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED,
cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT,
cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV,
cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1,
cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2,
cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT,
cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE,
cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK,
cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN,
cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING,
cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB,
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}
if enum is not None:
class Priority(enum.IntEnum):
ABOVE_NORMAL_PRIORITY_CLASS = ABOVE_NORMAL_PRIORITY_CLASS
BELOW_NORMAL_PRIORITY_CLASS = BELOW_NORMAL_PRIORITY_CLASS
HIGH_PRIORITY_CLASS = HIGH_PRIORITY_CLASS
IDLE_PRIORITY_CLASS = IDLE_PRIORITY_CLASS
NORMAL_PRIORITY_CLASS = NORMAL_PRIORITY_CLASS
REALTIME_PRIORITY_CLASS = REALTIME_PRIORITY_CLASS
globals().update(Priority.__members__)
if enum is None:
IOPRIO_VERYLOW = 0
IOPRIO_LOW = 1
IOPRIO_NORMAL = 2
IOPRIO_HIGH = 3
else:
class IOPriority(enum.IntEnum):
IOPRIO_VERYLOW = 0
IOPRIO_LOW = 1
IOPRIO_NORMAL = 2
IOPRIO_HIGH = 3
globals().update(IOPriority.__members__)
pinfo_map = dict(
num_handles=0,
ctx_switches=1,
user_time=2,
kernel_time=3,
create_time=4,
num_threads=5,
io_rcount=6,
io_wcount=7,
io_rbytes=8,
io_wbytes=9,
io_count_others=10,
io_bytes_others=11,
num_page_faults=12,
peak_wset=13,
wset=14,
peak_paged_pool=15,
paged_pool=16,
peak_non_paged_pool=17,
non_paged_pool=18,
pagefile=19,
peak_pagefile=20,
mem_private=21,
)
# =====================================================================
# --- named tuples
# =====================================================================
# psutil.cpu_times()
scputimes = namedtuple('scputimes',
['user', 'system', 'idle', 'interrupt', 'dpc'])
# psutil.virtual_memory()
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
# psutil.Process.memory_info()
pmem = namedtuple(
'pmem', ['rss', 'vms',
'num_page_faults', 'peak_wset', 'wset', 'peak_paged_pool',
'paged_pool', 'peak_nonpaged_pool', 'nonpaged_pool',
'pagefile', 'peak_pagefile', 'private'])
# psutil.Process.memory_full_info()
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss'])
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
# psutil.Process.io_counters()
pio = namedtuple('pio', ['read_count', 'write_count',
'read_bytes', 'write_bytes',
'other_count', 'other_bytes'])
# =====================================================================
# --- utils
# =====================================================================
@lru_cache(maxsize=512)
def convert_dos_path(s):
r"""Convert paths using native DOS format like:
"\Device\HarddiskVolume1\Windows\systemew\file.txt"
into:
"C:\Windows\systemew\file.txt"
"""
rawdrive = '\\'.join(s.split('\\')[:3])
driveletter = cext.QueryDosDevice(rawdrive)
remainder = s[len(rawdrive):]
return os.path.join(driveletter, remainder)
def py2_strencode(s):
"""Encode a unicode string to a byte string by using the default fs
encoding + "replace" error handler.
"""
if PY3:
return s
else:
if isinstance(s, str):
return s
else:
return s.encode(ENCODING, ENCODING_ERRS)
@memoize
def getpagesize():
return cext.getpagesize()
# =====================================================================
# --- memory
# =====================================================================
def virtual_memory():
"""System virtual memory as a namedtuple."""
mem = cext.virtual_mem()
totphys, availphys, totsys, availsys = mem
#
total = totphys
avail = availphys
free = availphys
used = total - avail
percent = usage_percent((total - avail), total, round_=1)
return svmem(total, avail, percent, used, free)
def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
mem = cext.virtual_mem()
total_phys = mem[0]
total_system = mem[2]
# system memory (commit total/limit) is the sum of physical and swap
# thus physical memory values need to be subtracted to get swap values
total = total_system - total_phys
# commit total is incremented immediately (decrementing free_system)
# while the corresponding free physical value is not decremented until
# pages are accessed, so we can't use free system memory for swap.
# instead, we calculate page file usage based on performance counter
if (total > 0):
percentswap = cext.swap_percent()
used = int(0.01 * percentswap * total)
else:
used = 0
free = total - used
percent = round(percentswap, 1)
return _common.sswap(total, used, free, percent, 0, 0)
# =====================================================================
# --- disk
# =====================================================================
disk_io_counters = cext.disk_io_counters
def disk_usage(path):
"""Return disk usage associated with path."""
if PY3 and isinstance(path, bytes):
# XXX: do we want to use "strict"? Probably yes, in order
# to fail immediately. After all we are accepting input here...
path = path.decode(ENCODING, errors="strict")
total, free = cext.disk_usage(path)
used = total - free
percent = usage_percent(used, total, round_=1)
return _common.sdiskusage(total, used, free, percent)
def disk_partitions(all):
"""Return disk partitions."""
rawlist = cext.disk_partitions(all)
return [_common.sdiskpart(*x) for x in rawlist]
# =====================================================================
# --- CPU
# =====================================================================
def cpu_times():
"""Return system CPU times as a named tuple."""
user, system, idle = cext.cpu_times()
# Internally, GetSystemTimes() is used, and it doesn't return
# interrupt and dpc times. cext.per_cpu_times() does, so we
# rely on it to get those only.
percpu_summed = scputimes(*[sum(n) for n in zip(*cext.per_cpu_times())])
return scputimes(user, system, idle,
percpu_summed.interrupt, percpu_summed.dpc)
def per_cpu_times():
"""Return system per-CPU times as a list of named tuples."""
ret = []
for user, system, idle, interrupt, dpc in cext.per_cpu_times():
item = scputimes(user, system, idle, interrupt, dpc)
ret.append(item)
return ret
def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
return cext.cpu_count_logical()
def cpu_count_cores():
"""Return the number of CPU cores in the system."""
return cext.cpu_count_cores()
def cpu_stats():
"""Return CPU statistics."""
ctx_switches, interrupts, dpcs, syscalls = cext.cpu_stats()
soft_interrupts = 0
return _common.scpustats(ctx_switches, interrupts, soft_interrupts,
syscalls)
def cpu_freq():
"""Return CPU frequency.
On Windows per-cpu frequency is not supported.
"""
curr, max_ = cext.cpu_freq()
min_ = 0.0
return [_common.scpufreq(float(curr), min_, float(max_))]
_loadavg_inititialized = False
def getloadavg():
"""Return the number of processes in the system run queue averaged
over the last 1, 5, and 15 minutes respectively as a tuple"""
global _loadavg_inititialized
if not _loadavg_inititialized:
cext.init_loadavg_counter()
_loadavg_inititialized = True
# Drop to 2 decimal points which is what Linux does
raw_loads = cext.getloadavg()
return tuple([round(load, 2) for load in raw_loads])
# =====================================================================
# --- network
# =====================================================================
def net_connections(kind, _pid=-1):
"""Return socket connections. If pid == -1 return system-wide
connections (as opposed to connections opened by one process only).
"""
if kind not in conn_tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in conn_tmap])))
families, types = conn_tmap[kind]
rawlist = cext.net_connections(_pid, families, types)
ret = set()
for item in rawlist:
fd, fam, type, laddr, raddr, status, pid = item
nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status, TCP_STATUSES,
pid=pid if _pid == -1 else None)
ret.add(nt)
return list(ret)
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
ret = {}
rawdict = cext.net_if_stats()
for name, items in rawdict.items():
if not PY3:
assert isinstance(name, unicode), type(name)
name = py2_strencode(name)
isup, duplex, speed, mtu = items
if hasattr(_common, 'NicDuplex'):
duplex = _common.NicDuplex(duplex)
ret[name] = _common.snicstats(isup, duplex, speed, mtu, '')
return ret
def net_io_counters():
"""Return network I/O statistics for every network interface
installed on the system as a dict of raw tuples.
"""
ret = cext.net_io_counters()
return dict([(py2_strencode(k), v) for k, v in ret.items()])
def net_if_addrs():
"""Return the addresses associated to each NIC."""
ret = []
for items in cext.net_if_addrs():
items = list(items)
items[0] = py2_strencode(items[0])
ret.append(items)
return ret
# =====================================================================
# --- sensors
# =====================================================================
def sensors_battery():
"""Return battery information."""
# For constants meaning see:
# https://msdn.microsoft.com/en-us/library/windows/desktop/
# aa373232(v=vs.85).aspx
acline_status, flags, percent, secsleft = cext.sensors_battery()
power_plugged = acline_status == 1
no_battery = bool(flags & 128)
charging = bool(flags & 8)
if no_battery:
return None
if power_plugged or charging:
secsleft = _common.POWER_TIME_UNLIMITED
elif secsleft == -1:
secsleft = _common.POWER_TIME_UNKNOWN
return _common.sbattery(percent, secsleft, power_plugged)
# =====================================================================
# --- other system functions
# =====================================================================
_last_btime = 0
def boot_time():
"""The system boot time expressed in seconds since the epoch."""
# This dirty hack is to adjust the precision of the returned
# value which may have a 1 second fluctuation, see:
# https://github.com/giampaolo/psutil/issues/1007
global _last_btime
ret = float(cext.boot_time())
if abs(ret - _last_btime) <= 1:
return _last_btime
else:
_last_btime = ret
return ret
def users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = cext.users()
for item in rawlist:
user, hostname, tstamp = item
user = py2_strencode(user)
nt = _common.suser(user, None, hostname, tstamp, None)
retlist.append(nt)
return retlist
# =====================================================================
# --- Windows services
# =====================================================================
def win_service_iter():
"""Yields a list of WindowsService instances."""
for name, display_name in cext.winservice_enumerate():
yield WindowsService(py2_strencode(name), py2_strencode(display_name))
def win_service_get(name):
"""Open a Windows service and return it as a WindowsService instance."""
service = WindowsService(name, None)
service._display_name = service._query_config()['display_name']
return service
class WindowsService(object):
"""Represents an installed Windows service."""
def __init__(self, name, display_name):
self._name = name
self._display_name = display_name
def __str__(self):
details = "(name=%r, display_name=%r)" % (
self._name, self._display_name)
return "%s%s" % (self.__class__.__name__, details)
def __repr__(self):
return "<%s at %s>" % (self.__str__(), id(self))
def __eq__(self, other):
# Test for equality with another WindosService object based
# on name.
if not isinstance(other, WindowsService):
return NotImplemented
return self._name == other._name
def __ne__(self, other):
return not self == other
def _query_config(self):
with self._wrap_exceptions():
display_name, binpath, username, start_type = \
cext.winservice_query_config(self._name)
# XXX - update _self.display_name?
return dict(
display_name=py2_strencode(display_name),
binpath=py2_strencode(binpath),
username=py2_strencode(username),
start_type=py2_strencode(start_type))
def _query_status(self):
with self._wrap_exceptions():
status, pid = cext.winservice_query_status(self._name)
if pid == 0:
pid = None
return dict(status=status, pid=pid)
@contextlib.contextmanager
def _wrap_exceptions(self):
"""Ctx manager which translates bare OSError and WindowsError
exceptions into NoSuchProcess and AccessDenied.
"""
try:
yield
except OSError as err:
if is_permission_err(err):
raise AccessDenied(
pid=None, name=self._name,
msg="service %r is not querable (not enough privileges)" %
self._name)
elif err.winerror in (cext.ERROR_INVALID_NAME,
cext.ERROR_SERVICE_DOES_NOT_EXIST):
raise NoSuchProcess(
pid=None, name=self._name,
msg="service %r does not exist)" % self._name)
else:
raise
# config query
def name(self):
"""The service name. This string is how a service is referenced
and can be passed to win_service_get() to get a new
WindowsService instance.
"""
return self._name
def display_name(self):
"""The service display name. The value is cached when this class
is instantiated.
"""
return self._display_name
def binpath(self):
"""The fully qualified path to the service binary/exe file as
a string, including command line arguments.
"""
return self._query_config()['binpath']
def username(self):
"""The name of the user that owns this service."""
return self._query_config()['username']
def start_type(self):
"""A string which can either be "automatic", "manual" or
"disabled".
"""
return self._query_config()['start_type']
# status query
def pid(self):
"""The process PID, if any, else None. This can be passed
to Process class to control the service's process.
"""
return self._query_status()['pid']
def status(self):
"""Service status as a string."""
return self._query_status()['status']
def description(self):
"""Service long description."""
return py2_strencode(cext.winservice_query_descr(self.name()))
# utils
def as_dict(self):
"""Utility method retrieving all the information above as a
dictionary.
"""
d = self._query_config()
d.update(self._query_status())
d['name'] = self.name()
d['display_name'] = self.display_name()
d['description'] = self.description()
return d
# actions
# XXX: the necessary C bindings for start() and stop() are
# implemented but for now I prefer not to expose them.
# I may change my mind in the future. Reasons:
# - they require Administrator privileges
# - can't implement a timeout for stop() (unless by using a thread,
# which sucks)
# - would require adding ServiceAlreadyStarted and
# ServiceAlreadyStopped exceptions, adding two new APIs.
# - we might also want to have modify(), which would basically mean
# rewriting win32serviceutil.ChangeServiceConfig, which involves a
# lot of stuff (and API constants which would pollute the API), see:
# http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/
# win32/lib/win32serviceutil.py.html#0175
# - psutil is typically about "read only" monitoring stuff;
# win_service_* APIs should only be used to retrieve a service and
# check whether it's running
# def start(self, timeout=None):
# with self._wrap_exceptions():
# cext.winservice_start(self.name())
# if timeout:
# giveup_at = time.time() + timeout
# while True:
# if self.status() == "running":
# return
# else:
# if time.time() > giveup_at:
# raise TimeoutExpired(timeout)
# else:
# time.sleep(.1)
# def stop(self):
# # Note: timeout is not implemented because it's just not
# # possible, see:
# # http://stackoverflow.com/questions/11973228/
# with self._wrap_exceptions():
# return cext.winservice_stop(self.name())
# =====================================================================
# --- processes
# =====================================================================
pids = cext.pids
pid_exists = cext.pid_exists
ppid_map = cext.ppid_map # used internally by Process.children()
def is_permission_err(exc):
"""Return True if this is a permission error."""
assert isinstance(exc, OSError), exc
# On Python 2 OSError doesn't always have 'winerror'. Sometimes
# it does, in which case the original exception was WindowsError
# (which is a subclass of OSError).
return exc.errno in (errno.EPERM, errno.EACCES) or \
getattr(exc, "winerror", -1) in (cext.ERROR_ACCESS_DENIED,
cext.ERROR_PRIVILEGE_NOT_HELD)
def convert_oserror(exc, pid=None, name=None):
"""Convert OSError into NoSuchProcess or AccessDenied."""
assert isinstance(exc, OSError), exc
if is_permission_err(exc):
return AccessDenied(pid=pid, name=name)
if exc.errno == errno.ESRCH:
return NoSuchProcess(pid=pid, name=name)
raise exc
def wrap_exceptions(fun):
"""Decorator which converts OSError into NoSuchProcess or AccessDenied."""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except OSError as err:
raise convert_oserror(err, pid=self.pid, name=self._name)
return wrapper
def retry_error_partial_copy(fun):
"""Workaround for https://github.com/giampaolo/psutil/issues/875.
See: https://stackoverflow.com/questions/4457745#4457745
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
delay = 0.0001
times = 33
for _ in range(times): # retries for roughly 1 second
try:
return fun(self, *args, **kwargs)
except WindowsError as _:
err = _
if err.winerror == ERROR_PARTIAL_COPY:
time.sleep(delay)
delay = min(delay * 2, 0.04)
continue
else:
raise
else:
msg = "%s retried %s times, converted to AccessDenied as it's " \
"still returning %r" % (fun, times, err)
raise AccessDenied(pid=self.pid, name=self._name, msg=msg)
return wrapper
class Process(object):
"""Wrapper class around underlying C implementation."""
__slots__ = ["pid", "_name", "_ppid", "_cache"]
def __init__(self, pid):
self.pid = pid
self._name = None
self._ppid = None
# --- oneshot() stuff
def oneshot_enter(self):
self._proc_info.cache_activate(self)
self.exe.cache_activate(self)
def oneshot_exit(self):
self._proc_info.cache_deactivate(self)
self.exe.cache_deactivate(self)
@memoize_when_activated
def _proc_info(self):
"""Return multiple information about this process as a
raw tuple.
"""
ret = cext.proc_info(self.pid)
assert len(ret) == len(pinfo_map)
return ret
def name(self):
"""Return process name, which on Windows is always the final
part of the executable.
"""
# This is how PIDs 0 and 4 are always represented in taskmgr
# and process-hacker.
if self.pid == 0:
return "System Idle Process"
if self.pid == 4:
return "System"
return os.path.basename(self.exe())
@wrap_exceptions
@memoize_when_activated
def exe(self):
if PYPY:
try:
exe = cext.proc_exe(self.pid)
except WindowsError as err:
# 24 = ERROR_TOO_MANY_OPEN_FILES. Not sure why this happens
# (perhaps PyPy's JIT delaying garbage collection of files?).
if err.errno == 24:
debug("%r translated into AccessDenied" % err)
raise AccessDenied(self.pid, self._name)
raise
else:
exe = cext.proc_exe(self.pid)
if not PY3:
exe = py2_strencode(exe)
if exe.startswith('\\'):
return convert_dos_path(exe)
return exe # May be "Registry", "MemCompression", ...
@wrap_exceptions
@retry_error_partial_copy
def cmdline(self):
if cext.WINVER >= cext.WINDOWS_8_1:
# PEB method detects cmdline changes but requires more
# privileges: https://github.com/giampaolo/psutil/pull/1398
try:
ret = cext.proc_cmdline(self.pid, use_peb=True)
except OSError as err:
if is_permission_err(err):
ret = cext.proc_cmdline(self.pid, use_peb=False)
else:
raise
else:
ret = cext.proc_cmdline(self.pid, use_peb=True)
if PY3:
return ret
else:
return [py2_strencode(s) for s in ret]
@wrap_exceptions
@retry_error_partial_copy
def environ(self):
ustr = cext.proc_environ(self.pid)
if ustr and not PY3:
assert isinstance(ustr, unicode), type(ustr)
return parse_environ_block(py2_strencode(ustr))
def ppid(self):
try:
return ppid_map()[self.pid]
except KeyError:
raise NoSuchProcess(self.pid, self._name)
def _get_raw_meminfo(self):
try:
return cext.proc_memory_info(self.pid)
except OSError as err:
if is_permission_err(err):
# TODO: the C ext can probably be refactored in order
# to get this from cext.proc_info()
info = self._proc_info()
return (
info[pinfo_map['num_page_faults']],
info[pinfo_map['peak_wset']],
info[pinfo_map['wset']],
info[pinfo_map['peak_paged_pool']],
info[pinfo_map['paged_pool']],
info[pinfo_map['peak_non_paged_pool']],
info[pinfo_map['non_paged_pool']],
info[pinfo_map['pagefile']],
info[pinfo_map['peak_pagefile']],
info[pinfo_map['mem_private']],
)
raise
@wrap_exceptions
def memory_info(self):
# on Windows RSS == WorkingSetSize and VSM == PagefileUsage.
# Underlying C function returns fields of PROCESS_MEMORY_COUNTERS
# struct.
t = self._get_raw_meminfo()
rss = t[2] # wset
vms = t[7] # pagefile
return pmem(*(rss, vms, ) + t)
@wrap_exceptions
def memory_full_info(self):
basic_mem = self.memory_info()
uss = cext.proc_memory_uss(self.pid)
uss *= getpagesize()
return pfullmem(*basic_mem + (uss, ))
def memory_maps(self):
try:
raw = cext.proc_memory_maps(self.pid)
except OSError as err:
# XXX - can't use wrap_exceptions decorator as we're
# returning a generator; probably needs refactoring.
raise convert_oserror(err, self.pid, self._name)
else:
for addr, perm, path, rss in raw:
path = convert_dos_path(path)
if not PY3:
path = py2_strencode(path)
addr = hex(addr)
yield (addr, perm, path, rss)
@wrap_exceptions
def kill(self):
return cext.proc_kill(self.pid)
@wrap_exceptions
def send_signal(self, sig):
if sig == signal.SIGTERM:
cext.proc_kill(self.pid)
# py >= 2.7
elif sig in (getattr(signal, "CTRL_C_EVENT", object()),
getattr(signal, "CTRL_BREAK_EVENT", object())):
os.kill(self.pid, sig)
else:
raise ValueError(
"only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals "
"are supported on Windows")
@wrap_exceptions
def wait(self, timeout=None):
if timeout is None:
cext_timeout = cext.INFINITE
else:
# WaitForSingleObject() expects time in milliseconds.
cext_timeout = int(timeout * 1000)
timer = getattr(time, 'monotonic', time.time)
stop_at = timer() + timeout if timeout is not None else None
try:
# Exit code is supposed to come from GetExitCodeProcess().
# May also be None if OpenProcess() failed with
# ERROR_INVALID_PARAMETER, meaning PID is already gone.
exit_code = cext.proc_wait(self.pid, cext_timeout)
except cext.TimeoutExpired:
# WaitForSingleObject() returned WAIT_TIMEOUT. Just raise.
raise TimeoutExpired(timeout, self.pid, self._name)
except cext.TimeoutAbandoned:
# WaitForSingleObject() returned WAIT_ABANDONED, see:
# https://github.com/giampaolo/psutil/issues/1224
# We'll just rely on the internal polling and return None
# when the PID disappears. Subprocess module does the same
# (return None):
# https://github.com/python/cpython/blob/
# be50a7b627d0aa37e08fa8e2d5568891f19903ce/
# Lib/subprocess.py#L1193-L1194
exit_code = None
# At this point WaitForSingleObject() returned WAIT_OBJECT_0,
# meaning the process is gone. Stupidly there are cases where
# its PID may still stick around so we do a further internal
# polling.
delay = 0.0001
while True:
if not pid_exists(self.pid):
return exit_code
if stop_at and timer() >= stop_at:
raise TimeoutExpired(timeout, pid=self.pid, name=self._name)
time.sleep(delay)
delay = min(delay * 2, 0.04) # incremental delay
@wrap_exceptions
def username(self):
if self.pid in (0, 4):
return 'NT AUTHORITY\\SYSTEM'
domain, user = cext.proc_username(self.pid)
return py2_strencode(domain) + '\\' + py2_strencode(user)
@wrap_exceptions
def create_time(self):
# Note: proc_times() not put under oneshot() 'cause create_time()
# is already cached by the main Process class.
try:
user, system, created = cext.proc_times(self.pid)
return created
except OSError as err:
if is_permission_err(err):
return self._proc_info()[pinfo_map['create_time']]
raise
@wrap_exceptions
def num_threads(self):
return self._proc_info()[pinfo_map['num_threads']]
@wrap_exceptions
def threads(self):
rawlist = cext.proc_threads(self.pid)
retlist = []
for thread_id, utime, stime in rawlist:
ntuple = _common.pthread(thread_id, utime, stime)
retlist.append(ntuple)
return retlist
@wrap_exceptions
def cpu_times(self):
try:
user, system, created = cext.proc_times(self.pid)
except OSError as err:
if not is_permission_err(err):
raise
info = self._proc_info()
user = info[pinfo_map['user_time']]
system = info[pinfo_map['kernel_time']]
# Children user/system times are not retrievable (set to 0).
return _common.pcputimes(user, system, 0.0, 0.0)
@wrap_exceptions
def suspend(self):
cext.proc_suspend_or_resume(self.pid, True)
@wrap_exceptions
def resume(self):
cext.proc_suspend_or_resume(self.pid, False)
@wrap_exceptions
@retry_error_partial_copy
def cwd(self):
if self.pid in (0, 4):
raise AccessDenied(self.pid, self._name)
# return a normalized pathname since the native C function appends
# "\\" at the and of the path
path = cext.proc_cwd(self.pid)
return py2_strencode(os.path.normpath(path))
@wrap_exceptions
def open_files(self):
if self.pid in (0, 4):
return []
ret = set()
# Filenames come in in native format like:
# "\Device\HarddiskVolume1\Windows\systemew\file.txt"
# Convert the first part in the corresponding drive letter
# (e.g. "C:\") by using Windows's QueryDosDevice()
raw_file_names = cext.proc_open_files(self.pid)
for _file in raw_file_names:
_file = convert_dos_path(_file)
if isfile_strict(_file):
if not PY3:
_file = py2_strencode(_file)
ntuple = _common.popenfile(_file, -1)
ret.add(ntuple)
return list(ret)
@wrap_exceptions
def connections(self, kind='inet'):
return net_connections(kind, _pid=self.pid)
@wrap_exceptions
def nice_get(self):
value = cext.proc_priority_get(self.pid)
if enum is not None:
value = Priority(value)
return value
@wrap_exceptions
def nice_set(self, value):
return cext.proc_priority_set(self.pid, value)
@wrap_exceptions
def ionice_get(self):
ret = cext.proc_io_priority_get(self.pid)
if enum is not None:
ret = IOPriority(ret)
return ret
@wrap_exceptions
def ionice_set(self, ioclass, value):
if value:
raise TypeError("value argument not accepted on Windows")
if ioclass not in (IOPRIO_VERYLOW, IOPRIO_LOW, IOPRIO_NORMAL,
IOPRIO_HIGH):
raise ValueError("%s is not a valid priority" % ioclass)
cext.proc_io_priority_set(self.pid, ioclass)
@wrap_exceptions
def io_counters(self):
try:
ret = cext.proc_io_counters(self.pid)
except OSError as err:
if not is_permission_err(err):
raise
info = self._proc_info()
ret = (
info[pinfo_map['io_rcount']],
info[pinfo_map['io_wcount']],
info[pinfo_map['io_rbytes']],
info[pinfo_map['io_wbytes']],
info[pinfo_map['io_count_others']],
info[pinfo_map['io_bytes_others']],
)
return pio(*ret)
@wrap_exceptions
def status(self):
suspended = cext.proc_is_suspended(self.pid)
if suspended:
return _common.STATUS_STOPPED
else:
return _common.STATUS_RUNNING
@wrap_exceptions
def cpu_affinity_get(self):
def from_bitmask(x):
return [i for i in range(64) if (1 << i) & x]
bitmask = cext.proc_cpu_affinity_get(self.pid)
return from_bitmask(bitmask)
@wrap_exceptions
def cpu_affinity_set(self, value):
def to_bitmask(ls):
if not ls:
raise ValueError("invalid argument %r" % ls)
out = 0
for b in ls:
out |= 2 ** b
return out
# SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
# is returned for an invalid CPU but this seems not to be true,
# therefore we check CPUs validy beforehand.
allcpus = list(range(len(per_cpu_times())))
for cpu in value:
if cpu not in allcpus:
if not isinstance(cpu, (int, long)):
raise TypeError(
"invalid CPU %r; an integer is required" % cpu)
else:
raise ValueError("invalid CPU %r" % cpu)
bitmask = to_bitmask(value)
cext.proc_cpu_affinity_set(self.pid, bitmask)
@wrap_exceptions
def num_handles(self):
try:
return cext.proc_num_handles(self.pid)
except OSError as err:
if is_permission_err(err):
return self._proc_info()[pinfo_map['num_handles']]
raise
@wrap_exceptions
def num_ctx_switches(self):
ctx_switches = self._proc_info()[pinfo_map['ctx_switches']]
# only voluntary ctx switches are supported
return _common.pctxsw(ctx_switches, 0)
| 37,424 | 32.38537 | 78 | py |
psutil | psutil-master/psutil/arch/aix/common.c | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/core.h>
#include <stdlib.h>
#include "common.h"
/* psutil_kread() - read from kernel memory */
int
psutil_kread(
int Kd, /* kernel memory file descriptor */
KA_T addr, /* kernel memory address */
char *buf, /* buffer to receive data */
size_t len) { /* length to read */
int br;
if (lseek64(Kd, (off64_t)addr, L_SET) == (off64_t)-1) {
PyErr_SetFromErrno(PyExc_OSError);
return 1;
}
br = read(Kd, buf, len);
if (br == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return 1;
}
if (br != len) {
PyErr_SetString(PyExc_RuntimeError,
"size mismatch when reading kernel memory fd");
return 1;
}
return 0;
}
struct procentry64 *
psutil_read_process_table(int * num) {
size_t msz;
pid32_t pid = 0;
struct procentry64 *processes = (struct procentry64 *)NULL;
struct procentry64 *p;
int Np = 0; /* number of processes allocated in 'processes' */
int np = 0; /* number of processes read into 'processes' */
int i; /* number of processes read in current iteration */
msz = (size_t)(PROCSIZE * PROCINFO_INCR);
processes = (struct procentry64 *)malloc(msz);
if (!processes) {
PyErr_NoMemory();
return NULL;
}
Np = PROCINFO_INCR;
p = processes;
while ((i = getprocs64(p, PROCSIZE, (struct fdsinfo64 *)NULL, 0, &pid,
PROCINFO_INCR))
== PROCINFO_INCR) {
np += PROCINFO_INCR;
if (np >= Np) {
msz = (size_t)(PROCSIZE * (Np + PROCINFO_INCR));
processes = (struct procentry64 *)realloc((char *)processes, msz);
if (!processes) {
PyErr_NoMemory();
return NULL;
}
Np += PROCINFO_INCR;
}
p = (struct procentry64 *)((char *)processes + (np * PROCSIZE));
}
/* add the number of processes read in the last iteration */
if (i > 0)
np += i;
*num = np;
return processes;
}
| 2,285 | 27.575 | 78 | c |
psutil | psutil-master/psutil/arch/aix/common.h | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef __PSUTIL_AIX_COMMON_H__
#define __PSUTIL_AIX_COMMON_H__
#include <sys/core.h>
#define PROCINFO_INCR (256)
#define PROCSIZE (sizeof(struct procentry64))
#define FDSINFOSIZE (sizeof(struct fdsinfo64))
#define KMEM "/dev/kmem"
typedef u_longlong_t KA_T;
/* psutil_kread() - read from kernel memory */
int psutil_kread(int Kd, /* kernel memory file descriptor */
KA_T addr, /* kernel memory address */
char *buf, /* buffer to receive data */
size_t len); /* length to read */
struct procentry64 *
psutil_read_process_table(
int * num /* out - number of processes read */
);
#endif /* __PSUTIL_AIX_COMMON_H__ */
| 894 | 26.96875 | 73 | h |
psutil | psutil-master/psutil/arch/aix/ifaddrs.c | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*! Based on code from
https://lists.samba.org/archive/samba-technical/2009-February/063079.html
!*/
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "ifaddrs.h"
#define MAX(x,y) ((x)>(y)?(x):(y))
#define SIZE(p) MAX((p).sa_len,sizeof(p))
static struct sockaddr *
sa_dup(struct sockaddr *sa1)
{
struct sockaddr *sa2;
size_t sz = sa1->sa_len;
sa2 = (struct sockaddr *) calloc(1, sz);
if (sa2 == NULL)
return NULL;
memcpy(sa2, sa1, sz);
return sa2;
}
void freeifaddrs(struct ifaddrs *ifp)
{
if (NULL == ifp) return;
free(ifp->ifa_name);
free(ifp->ifa_addr);
free(ifp->ifa_netmask);
free(ifp->ifa_dstaddr);
freeifaddrs(ifp->ifa_next);
free(ifp);
}
int getifaddrs(struct ifaddrs **ifap)
{
int sd, ifsize;
char *ccp, *ecp;
struct ifconf ifc;
struct ifreq *ifr;
struct ifaddrs *cifa = NULL; /* current */
struct ifaddrs *pifa = NULL; /* previous */
const size_t IFREQSZ = sizeof(struct ifreq);
int fam;
*ifap = NULL;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd == -1)
goto error;
/* find how much memory to allocate for the SIOCGIFCONF call */
if (ioctl(sd, SIOCGSIZIFCONF, (caddr_t)&ifsize) < 0)
goto error;
ifc.ifc_req = (struct ifreq *) calloc(1, ifsize);
if (ifc.ifc_req == NULL)
goto error;
ifc.ifc_len = ifsize;
if (ioctl(sd, SIOCGIFCONF, &ifc) < 0)
goto error;
ccp = (char *)ifc.ifc_req;
ecp = ccp + ifsize;
while (ccp < ecp) {
ifr = (struct ifreq *) ccp;
ifsize = sizeof(ifr->ifr_name) + SIZE(ifr->ifr_addr);
fam = ifr->ifr_addr.sa_family;
if (fam == AF_INET || fam == AF_INET6) {
cifa = (struct ifaddrs *) calloc(1, sizeof(struct ifaddrs));
if (cifa == NULL)
goto error;
cifa->ifa_next = NULL;
if (pifa == NULL) *ifap = cifa; /* first one */
else pifa->ifa_next = cifa;
cifa->ifa_name = strdup(ifr->ifr_name);
if (cifa->ifa_name == NULL)
goto error;
cifa->ifa_flags = 0;
cifa->ifa_dstaddr = NULL;
cifa->ifa_addr = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_addr == NULL)
goto error;
if (fam == AF_INET) {
if (ioctl(sd, SIOCGIFNETMASK, ifr, IFREQSZ) < 0)
goto error;
cifa->ifa_netmask = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_netmask == NULL)
goto error;
}
if (0 == ioctl(sd, SIOCGIFFLAGS, ifr)) /* optional */
cifa->ifa_flags = ifr->ifr_flags;
if (fam == AF_INET) {
if (ioctl(sd, SIOCGIFDSTADDR, ifr, IFREQSZ) < 0) {
if (0 == ioctl(sd, SIOCGIFBRDADDR, ifr, IFREQSZ)) {
cifa->ifa_dstaddr = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_dstaddr == NULL)
goto error;
}
}
else {
cifa->ifa_dstaddr = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_dstaddr == NULL)
goto error;
}
}
pifa = cifa;
}
ccp += ifsize;
}
free(ifc.ifc_req);
close(sd);
return 0;
error:
if (ifc.ifc_req != NULL)
free(ifc.ifc_req);
if (sd != -1)
close(sd);
freeifaddrs(*ifap);
return (-1);
}
| 3,840 | 24.606667 | 77 | c |
psutil | psutil-master/psutil/arch/aix/ifaddrs.h | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*! Based on code from
https://lists.samba.org/archive/samba-technical/2009-February/063079.html
!*/
#ifndef GENERIC_AIX_IFADDRS_H
#define GENERIC_AIX_IFADDRS_H
#include <sys/socket.h>
#include <net/if.h>
#undef ifa_dstaddr
#undef ifa_broadaddr
#define ifa_broadaddr ifa_dstaddr
struct ifaddrs {
struct ifaddrs *ifa_next;
char *ifa_name;
unsigned int ifa_flags;
struct sockaddr *ifa_addr;
struct sockaddr *ifa_netmask;
struct sockaddr *ifa_dstaddr;
};
extern int getifaddrs(struct ifaddrs **);
extern void freeifaddrs(struct ifaddrs *);
#endif
| 767 | 20.942857 | 77 | h |
psutil | psutil-master/psutil/arch/aix/net_connections.c | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Baded on code from lsof:
* http://www.ibm.com/developerworks/aix/library/au-lsof.html
* - dialects/aix/dproc.c:gather_proc_info
* - lib/prfp.c:process_file
* - dialects/aix/dsock.c:process_socket
* - dialects/aix/dproc.c:get_kernel_access
*/
#include <Python.h>
#include <stdlib.h>
#include <fcntl.h>
#define _KERNEL
#include <sys/file.h>
#undef _KERNEL
#include <sys/types.h>
#include <sys/core.h>
#include <sys/domain.h>
#include <sys/un.h>
#include <netinet/in_pcb.h>
#include <arpa/inet.h>
#include "../../_psutil_common.h"
#include "net_kernel_structs.h"
#include "net_connections.h"
#include "common.h"
#define NO_SOCKET (PyObject *)(-1)
static int
read_unp_addr(
int Kd,
KA_T unp_addr,
char *buf,
size_t buflen
) {
struct sockaddr_un *ua = (struct sockaddr_un *)NULL;
struct sockaddr_un un;
struct mbuf64 mb;
int uo;
if (psutil_kread(Kd, unp_addr, (char *)&mb, sizeof(mb))) {
return 1;
}
uo = (int)(mb.m_hdr.mh_data - unp_addr);
if ((uo + sizeof(struct sockaddr)) <= sizeof(mb))
ua = (struct sockaddr_un *)((char *)&mb + uo);
else {
if (psutil_kread(Kd, (KA_T)mb.m_hdr.mh_data,
(char *)&un, sizeof(un))) {
return 1;
}
ua = &un;
}
if (ua && ua->sun_path[0]) {
if (mb.m_len > sizeof(struct sockaddr_un))
mb.m_len = sizeof(struct sockaddr_un);
*((char *)ua + mb.m_len - 1) = '\0';
snprintf(buf, buflen, "%s", ua->sun_path);
}
return 0;
}
static PyObject *
process_file(int Kd, pid32_t pid, int fd, KA_T fp) {
struct file64 f;
struct socket64 s;
struct protosw64 p;
struct domain d;
struct inpcb64 inp;
int fam;
struct tcpcb64 t;
int state = PSUTIL_CONN_NONE;
unsigned char *laddr = (unsigned char *)NULL;
unsigned char *raddr = (unsigned char *)NULL;
int rport, lport;
char laddr_str[INET6_ADDRSTRLEN];
char raddr_str[INET6_ADDRSTRLEN];
struct unpcb64 unp;
char unix_laddr_str[PATH_MAX] = { 0 };
char unix_raddr_str[PATH_MAX] = { 0 };
/* Read file structure */
if (psutil_kread(Kd, fp, (char *)&f, sizeof(f))) {
return NULL;
}
if (!f.f_count || f.f_type != DTYPE_SOCKET) {
return NO_SOCKET;
}
if (psutil_kread(Kd, (KA_T) f.f_data, (char *) &s, sizeof(s))) {
return NULL;
}
if (!s.so_type) {
return NO_SOCKET;
}
if (!s.so_proto) {
PyErr_SetString(PyExc_RuntimeError, "invalid socket protocol handle");
return NULL;
}
if (psutil_kread(Kd, (KA_T)s.so_proto, (char *)&p, sizeof(p))) {
return NULL;
}
if (!p.pr_domain) {
PyErr_SetString(PyExc_RuntimeError, "invalid socket protocol domain");
return NULL;
}
if (psutil_kread(Kd, (KA_T)p.pr_domain, (char *)&d, sizeof(d))) {
return NULL;
}
fam = d.dom_family;
if (fam == AF_INET || fam == AF_INET6) {
/* Read protocol control block */
if (!s.so_pcb) {
PyErr_SetString(PyExc_RuntimeError, "invalid socket PCB");
return NULL;
}
if (psutil_kread(Kd, (KA_T) s.so_pcb, (char *) &inp, sizeof(inp))) {
return NULL;
}
if (p.pr_protocol == IPPROTO_TCP) {
/* If this is a TCP socket, read its control block */
if (inp.inp_ppcb
&& !psutil_kread(Kd, (KA_T)inp.inp_ppcb,
(char *)&t, sizeof(t)))
state = t.t_state;
}
if (fam == AF_INET6) {
laddr = (unsigned char *)&inp.inp_laddr6;
if (!IN6_IS_ADDR_UNSPECIFIED(&inp.inp_faddr6)) {
raddr = (unsigned char *)&inp.inp_faddr6;
rport = (int)ntohs(inp.inp_fport);
}
}
if (fam == AF_INET) {
laddr = (unsigned char *)&inp.inp_laddr;
if (inp.inp_faddr.s_addr != INADDR_ANY || inp.inp_fport != 0) {
raddr = (unsigned char *)&inp.inp_faddr;
rport = (int)ntohs(inp.inp_fport);
}
}
lport = (int)ntohs(inp.inp_lport);
inet_ntop(fam, laddr, laddr_str, sizeof(laddr_str));
if (raddr != NULL) {
inet_ntop(fam, raddr, raddr_str, sizeof(raddr_str));
return Py_BuildValue("(iii(si)(si)ii)", fd, fam,
s.so_type, laddr_str, lport, raddr_str,
rport, state, pid);
}
else {
return Py_BuildValue("(iii(si)()ii)", fd, fam,
s.so_type, laddr_str, lport, state,
pid);
}
}
if (fam == AF_UNIX) {
if (psutil_kread(Kd, (KA_T) s.so_pcb, (char *)&unp, sizeof(unp))) {
return NULL;
}
if ((KA_T) f.f_data != (KA_T) unp.unp_socket) {
PyErr_SetString(PyExc_RuntimeError, "unp_socket mismatch");
return NULL;
}
if (unp.unp_addr) {
if (read_unp_addr(Kd, unp.unp_addr, unix_laddr_str,
sizeof(unix_laddr_str))) {
return NULL;
}
}
if (unp.unp_conn) {
if (psutil_kread(Kd, (KA_T) unp.unp_conn, (char *)&unp,
sizeof(unp))) {
return NULL;
}
if (read_unp_addr(Kd, unp.unp_addr, unix_raddr_str,
sizeof(unix_raddr_str))) {
return NULL;
}
}
return Py_BuildValue("(iiissii)", fd, d.dom_family,
s.so_type, unix_laddr_str, unix_raddr_str, PSUTIL_CONN_NONE,
pid);
}
return NO_SOCKET;
}
PyObject *
psutil_net_connections(PyObject *self, PyObject *args) {
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
KA_T fp;
int Kd = -1;
int i, np;
struct procentry64 *p;
struct fdsinfo64 *fds = (struct fdsinfo64 *)NULL;
pid32_t requested_pid;
pid32_t pid;
struct procentry64 *processes = (struct procentry64 *)NULL;
/* the process table */
if (py_retlist == NULL)
goto error;
if (! PyArg_ParseTuple(args, "i", &requested_pid))
goto error;
Kd = open(KMEM, O_RDONLY, 0);
if (Kd < 0) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, KMEM);
goto error;
}
processes = psutil_read_process_table(&np);
if (!processes)
goto error;
/* Loop through processes */
for (p = processes; np > 0; np--, p++) {
pid = p->pi_pid;
if (requested_pid != -1 && requested_pid != pid)
continue;
if (p->pi_state == 0 || p->pi_state == SZOMB)
continue;
if (!fds) {
fds = (struct fdsinfo64 *)malloc((size_t)FDSINFOSIZE);
if (!fds) {
PyErr_NoMemory();
goto error;
}
}
if (getprocs64((struct procentry64 *)NULL, PROCSIZE, fds, FDSINFOSIZE,
&pid, 1)
!= 1)
continue;
/* loop over file descriptors */
for (i = 0; i < p->pi_maxofile; i++) {
fp = (KA_T)fds->pi_ufd[i].fp;
if (fp) {
py_tuple = process_file(Kd, p->pi_pid, i, fp);
if (py_tuple == NULL)
goto error;
if (py_tuple != NO_SOCKET) {
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
}
}
}
close(Kd);
free(processes);
if (fds != NULL)
free(fds);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (Kd > 0)
close(Kd);
if (processes != NULL)
free(processes);
if (fds != NULL)
free(fds);
return NULL;
}
| 8,134 | 27.246528 | 78 | c |
psutil | psutil-master/psutil/arch/aix/net_connections.h | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef __NET_CONNECTIONS_H__
#define __NET_CONNECTIONS_H__
#include <Python.h>
PyObject* psutil_net_connections(PyObject *self, PyObject *args);
#endif /* __NET_CONNECTIONS_H__ */
| 356 | 21.3125 | 73 | h |
psutil | psutil-master/psutil/arch/aix/net_kernel_structs.h | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* The kernel is always 64 bit but Python is usually compiled as a 32 bit
* process. We're reading the kernel memory to get the network connections,
* so we need the structs we read to be defined with 64 bit "pointers".
* Here are the partial definitions of the structs we use, taken from the
* header files, with data type sizes converted to their 64 bit counterparts,
* and unused data truncated. */
#ifdef __64BIT__
/* In case we're in a 64 bit process after all */
#include <sys/socketvar.h>
#include <sys/protosw.h>
#include <sys/unpcb.h>
#include <sys/mbuf_base.h>
#include <sys/mbuf_macro.h>
#include <netinet/ip_var.h>
#include <netinet/tcp.h>
#include <netinet/tcpip.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#define file64 file
#define socket64 socket
#define protosw64 protosw
#define inpcb64 inpcb
#define tcpcb64 tcpcb
#define unpcb64 unpcb
#define mbuf64 mbuf
#else /* __64BIT__ */
struct file64 {
int f_flag;
int f_count;
int f_options;
int f_type;
u_longlong_t f_data;
};
struct socket64 {
short so_type; /* generic type, see socket.h */
short so_options; /* from socket call, see socket.h */
ushort so_linger; /* time to linger while closing */
short so_state; /* internal state flags SS_*, below */
u_longlong_t so_pcb; /* protocol control block */
u_longlong_t so_proto; /* protocol handle */
};
struct protosw64 {
short pr_type; /* socket type used for */
u_longlong_t pr_domain; /* domain protocol a member of */
short pr_protocol; /* protocol number */
short pr_flags; /* see below */
};
struct inpcb64 {
u_longlong_t inp_next,inp_prev;
/* pointers to other pcb's */
u_longlong_t inp_head; /* pointer back to chain of inpcb's
for this protocol */
u_int32_t inp_iflowinfo; /* input flow label */
u_short inp_fport; /* foreign port */
u_int16_t inp_fatype; /* foreign address type */
union in_addr_6 inp_faddr_6; /* foreign host table entry */
u_int32_t inp_oflowinfo; /* output flow label */
u_short inp_lport; /* local port */
u_int16_t inp_latype; /* local address type */
union in_addr_6 inp_laddr_6; /* local host table entry */
u_longlong_t inp_socket; /* back pointer to socket */
u_longlong_t inp_ppcb; /* pointer to per-protocol pcb */
u_longlong_t space_rt;
struct sockaddr_in6 spare_dst;
u_longlong_t inp_ifa; /* interface address to use */
int inp_flags; /* generic IP/datagram flags */
};
struct tcpcb64 {
u_longlong_t seg__next;
u_longlong_t seg__prev;
short t_state; /* state of this connection */
};
struct unpcb64 {
u_longlong_t unp_socket; /* pointer back to socket */
u_longlong_t unp_vnode; /* if associated with file */
ino_t unp_vno; /* fake vnode number */
u_longlong_t unp_conn; /* control block of connected socket */
u_longlong_t unp_refs; /* referencing socket linked list */
u_longlong_t unp_nextref; /* link in unp_refs list */
u_longlong_t unp_addr; /* bound address of socket */
};
struct m_hdr64
{
u_longlong_t mh_next; /* next buffer in chain */
u_longlong_t mh_nextpkt; /* next chain in queue/record */
long mh_len; /* amount of data in this mbuf */
u_longlong_t mh_data; /* location of data */
};
struct mbuf64
{
struct m_hdr64 m_hdr;
};
#define m_len m_hdr.mh_len
#endif /* __64BIT__ */
| 4,060 | 35.258929 | 77 | h |
psutil | psutil-master/psutil/arch/bsd/cpu.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <sys/resource.h>
#include <sys/sched.h>
PyObject *
psutil_cpu_count_logical(PyObject *self, PyObject *args) {
int mib[2];
int ncpu;
size_t len;
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1)
Py_RETURN_NONE; // mimic os.cpu_count()
else
return Py_BuildValue("i", ncpu);
}
PyObject *
psutil_cpu_times(PyObject *self, PyObject *args) {
#ifdef PSUTIL_NETBSD
u_int64_t cpu_time[CPUSTATES];
#else
long cpu_time[CPUSTATES];
#endif
size_t size = sizeof(cpu_time);
int ret;
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_NETBSD)
ret = sysctlbyname("kern.cp_time", &cpu_time, &size, NULL, 0);
#elif PSUTIL_OPENBSD
int mib[] = {CTL_KERN, KERN_CPTIME};
ret = sysctl(mib, 2, &cpu_time, &size, NULL, 0);
#endif
if (ret == -1)
return PyErr_SetFromErrno(PyExc_OSError);
return Py_BuildValue("(ddddd)",
(double)cpu_time[CP_USER] / CLOCKS_PER_SEC,
(double)cpu_time[CP_NICE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_SYS] / CLOCKS_PER_SEC,
(double)cpu_time[CP_IDLE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_INTR] / CLOCKS_PER_SEC
);
}
| 1,552 | 26.732143 | 73 | c |
psutil | psutil-master/psutil/arch/bsd/cpu.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_cpu_count_logical(PyObject *self, PyObject *args);
PyObject *psutil_cpu_times(PyObject *self, PyObject *args);
| 335 | 29.545455 | 73 | h |
psutil | psutil-master/psutil/arch/bsd/disk.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/mount.h>
#if PSUTIL_NETBSD
// getvfsstat()
#include <sys/types.h>
#include <sys/statvfs.h>
#else
// getfsstat()
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#endif
PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
int num;
int i;
long len;
uint64_t flags;
char opts[200];
#ifdef PSUTIL_NETBSD
struct statvfs *fs = NULL;
#else
struct statfs *fs = NULL;
#endif
PyObject *py_retlist = PyList_New(0);
PyObject *py_dev = NULL;
PyObject *py_mountp = NULL;
PyObject *py_tuple = NULL;
if (py_retlist == NULL)
return NULL;
// get the number of mount points
Py_BEGIN_ALLOW_THREADS
#ifdef PSUTIL_NETBSD
num = getvfsstat(NULL, 0, MNT_NOWAIT);
#else
num = getfsstat(NULL, 0, MNT_NOWAIT);
#endif
Py_END_ALLOW_THREADS
if (num == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
len = sizeof(*fs) * num;
fs = malloc(len);
if (fs == NULL) {
PyErr_NoMemory();
goto error;
}
Py_BEGIN_ALLOW_THREADS
#ifdef PSUTIL_NETBSD
num = getvfsstat(fs, len, MNT_NOWAIT);
#else
num = getfsstat(fs, len, MNT_NOWAIT);
#endif
Py_END_ALLOW_THREADS
if (num == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < num; i++) {
py_tuple = NULL;
opts[0] = 0;
#ifdef PSUTIL_NETBSD
flags = fs[i].f_flag;
#else
flags = fs[i].f_flags;
#endif
// see sys/mount.h
if (flags & MNT_RDONLY)
strlcat(opts, "ro", sizeof(opts));
else
strlcat(opts, "rw", sizeof(opts));
if (flags & MNT_SYNCHRONOUS)
strlcat(opts, ",sync", sizeof(opts));
if (flags & MNT_NOEXEC)
strlcat(opts, ",noexec", sizeof(opts));
if (flags & MNT_NOSUID)
strlcat(opts, ",nosuid", sizeof(opts));
if (flags & MNT_ASYNC)
strlcat(opts, ",async", sizeof(opts));
if (flags & MNT_NOATIME)
strlcat(opts, ",noatime", sizeof(opts));
if (flags & MNT_SOFTDEP)
strlcat(opts, ",softdep", sizeof(opts));
#ifdef PSUTIL_FREEBSD
if (flags & MNT_UNION)
strlcat(opts, ",union", sizeof(opts));
if (flags & MNT_SUIDDIR)
strlcat(opts, ",suiddir", sizeof(opts));
if (flags & MNT_SOFTDEP)
strlcat(opts, ",softdep", sizeof(opts));
if (flags & MNT_NOSYMFOLLOW)
strlcat(opts, ",nosymfollow", sizeof(opts));
#ifdef MNT_GJOURNAL
if (flags & MNT_GJOURNAL)
strlcat(opts, ",gjournal", sizeof(opts));
#endif
if (flags & MNT_MULTILABEL)
strlcat(opts, ",multilabel", sizeof(opts));
if (flags & MNT_ACLS)
strlcat(opts, ",acls", sizeof(opts));
if (flags & MNT_NOCLUSTERR)
strlcat(opts, ",noclusterr", sizeof(opts));
if (flags & MNT_NOCLUSTERW)
strlcat(opts, ",noclusterw", sizeof(opts));
#ifdef MNT_NFS4ACLS
if (flags & MNT_NFS4ACLS)
strlcat(opts, ",nfs4acls", sizeof(opts));
#endif
#elif PSUTIL_NETBSD
if (flags & MNT_NODEV)
strlcat(opts, ",nodev", sizeof(opts));
if (flags & MNT_UNION)
strlcat(opts, ",union", sizeof(opts));
if (flags & MNT_NOCOREDUMP)
strlcat(opts, ",nocoredump", sizeof(opts));
#ifdef MNT_RELATIME
if (flags & MNT_RELATIME)
strlcat(opts, ",relatime", sizeof(opts));
#endif
if (flags & MNT_IGNORE)
strlcat(opts, ",ignore", sizeof(opts));
#ifdef MNT_DISCARD
if (flags & MNT_DISCARD)
strlcat(opts, ",discard", sizeof(opts));
#endif
#ifdef MNT_EXTATTR
if (flags & MNT_EXTATTR)
strlcat(opts, ",extattr", sizeof(opts));
#endif
if (flags & MNT_LOG)
strlcat(opts, ",log", sizeof(opts));
if (flags & MNT_SYMPERM)
strlcat(opts, ",symperm", sizeof(opts));
if (flags & MNT_NODEVMTIME)
strlcat(opts, ",nodevmtime", sizeof(opts));
#endif
py_dev = PyUnicode_DecodeFSDefault(fs[i].f_mntfromname);
if (! py_dev)
goto error;
py_mountp = PyUnicode_DecodeFSDefault(fs[i].f_mntonname);
if (! py_mountp)
goto error;
py_tuple = Py_BuildValue("(OOss)",
py_dev, // device
py_mountp, // mount point
fs[i].f_fstypename, // fs type
opts); // options
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_dev);
Py_CLEAR(py_mountp);
Py_CLEAR(py_tuple);
}
free(fs);
return py_retlist;
error:
Py_XDECREF(py_dev);
Py_XDECREF(py_mountp);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (fs != NULL)
free(fs);
return NULL;
}
| 5,271 | 27.652174 | 73 | c |
psutil | psutil-master/psutil/arch/bsd/disk.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_disk_partitions(PyObject *self, PyObject *args);
| 273 | 26.4 | 73 | h |
psutil | psutil-master/psutil/arch/bsd/net.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <string.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/route.h>
PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args) {
char *buf = NULL, *lim, *next;
struct if_msghdr *ifm;
int mib[6];
size_t len;
PyObject *py_retdict = PyDict_New();
PyObject *py_ifc_info = NULL;
if (py_retdict == NULL)
return NULL;
mib[0] = CTL_NET; // networking subsystem
mib[1] = PF_ROUTE; // type of information
mib[2] = 0; // protocol (IPPROTO_xxx)
mib[3] = 0; // address family
mib[4] = NET_RT_IFLIST; // operation
mib[5] = 0;
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
buf = malloc(len);
if (buf == NULL) {
PyErr_NoMemory();
goto error;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
lim = buf + len;
for (next = buf; next < lim; ) {
py_ifc_info = NULL;
ifm = (struct if_msghdr *)next;
next += ifm->ifm_msglen;
if (ifm->ifm_type == RTM_IFINFO) {
struct if_msghdr *if2m = (struct if_msghdr *)ifm;
struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
char ifc_name[32];
strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);
ifc_name[sdl->sdl_nlen] = 0;
// XXX: ignore usbus interfaces:
// http://lists.freebsd.org/pipermail/freebsd-current/
// 2011-October/028752.html
// 'ifconfig -a' doesn't show them, nor do we.
if (strncmp(ifc_name, "usbus", 5) == 0)
continue;
py_ifc_info = Py_BuildValue("(kkkkkkki)",
if2m->ifm_data.ifi_obytes,
if2m->ifm_data.ifi_ibytes,
if2m->ifm_data.ifi_opackets,
if2m->ifm_data.ifi_ipackets,
if2m->ifm_data.ifi_ierrors,
if2m->ifm_data.ifi_oerrors,
if2m->ifm_data.ifi_iqdrops,
#ifdef _IFI_OQDROPS
if2m->ifm_data.ifi_oqdrops
#else
0
#endif
);
if (!py_ifc_info)
goto error;
if (PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info))
goto error;
Py_CLEAR(py_ifc_info);
}
else {
continue;
}
}
free(buf);
return py_retdict;
error:
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (buf != NULL)
free(buf);
return NULL;
}
| 3,121 | 28.45283 | 73 | c |
psutil | psutil-master/psutil/arch/bsd/net.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_net_io_counters(PyObject *self, PyObject *args);
| 273 | 26.4 | 73 | h |
psutil | psutil-master/psutil/arch/bsd/proc.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <kvm.h>
#include <sys/proc.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/vnode.h> // VREG
#ifdef PSUTIL_FREEBSD
#include <sys/user.h> // kinfo_proc, kinfo_file, KF_*
#include <libutil.h> // kinfo_getfile()
#endif
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#ifdef PSUTIL_FREEBSD
#include "../../arch/freebsd/proc.h"
#elif PSUTIL_OPENBSD
#include "../../arch/openbsd/proc.h"
#elif PSUTIL_NETBSD
#include "../../arch/netbsd/proc.h"
#endif
// convert a timeval struct to a double
#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
#if defined(PSUTIL_OPENBSD) || defined (PSUTIL_NETBSD)
#define PSUTIL_KPT2DOUBLE(t) (t ## _sec + t ## _usec / 1000000.0)
#endif
/*
* Return a Python list of all the PIDs running on the system.
*/
PyObject *
psutil_pids(PyObject *self, PyObject *args) {
kinfo_proc *proclist = NULL;
kinfo_proc *orig_address = NULL;
size_t num_processes;
size_t idx;
PyObject *py_retlist = PyList_New(0);
PyObject *py_pid = NULL;
if (py_retlist == NULL)
return NULL;
if (psutil_get_proc_list(&proclist, &num_processes) != 0)
goto error;
if (num_processes > 0) {
orig_address = proclist; // save so we can free it after we're done
for (idx = 0; idx < num_processes; idx++) {
#ifdef PSUTIL_FREEBSD
py_pid = PyLong_FromPid(proclist->ki_pid);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
py_pid = PyLong_FromPid(proclist->p_pid);
#endif
if (!py_pid)
goto error;
if (PyList_Append(py_retlist, py_pid))
goto error;
Py_CLEAR(py_pid);
proclist++;
}
free(orig_address);
}
return py_retlist;
error:
Py_XDECREF(py_pid);
Py_DECREF(py_retlist);
if (orig_address != NULL)
free(orig_address);
return NULL;
}
/*
* Collect different info about a process in one shot and return
* them as a big Python tuple.
*/
PyObject *
psutil_proc_oneshot_info(PyObject *self, PyObject *args) {
pid_t pid;
long rss;
long vms;
long memtext;
long memdata;
long memstack;
int oncpu;
kinfo_proc kp;
long pagesize = psutil_getpagesize();
char str[1000];
PyObject *py_name;
PyObject *py_ppid;
PyObject *py_retlist;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
// Process
#ifdef PSUTIL_FREEBSD
sprintf(str, "%s", kp.ki_comm);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
sprintf(str, "%s", kp.p_comm);
#endif
py_name = PyUnicode_DecodeFSDefault(str);
if (! py_name) {
// Likely a decoding error. We don't want to fail the whole
// operation. The python module may retry with proc_name().
PyErr_Clear();
py_name = Py_None;
}
// Py_INCREF(py_name);
// Calculate memory.
#ifdef PSUTIL_FREEBSD
rss = (long)kp.ki_rssize * pagesize;
vms = (long)kp.ki_size;
memtext = (long)kp.ki_tsize * pagesize;
memdata = (long)kp.ki_dsize * pagesize;
memstack = (long)kp.ki_ssize * pagesize;
#else
rss = (long)kp.p_vm_rssize * pagesize;
#ifdef PSUTIL_OPENBSD
// VMS, this is how ps determines it on OpenBSD:
// https://github.com/openbsd/src/blob/
// 588f7f8c69786211f2d16865c552afb91b1c7cba/bin/ps/print.c#L505
vms = (long)(kp.p_vm_dsize + kp.p_vm_ssize + kp.p_vm_tsize) * pagesize;
#elif PSUTIL_NETBSD
// VMS, this is how top determines it on NetBSD:
// https://github.com/IIJ-NetBSD/netbsd-src/blob/master/external/
// bsd/top/dist/machine/m_netbsd.c
vms = (long)kp.p_vm_msize * pagesize;
#endif
memtext = (long)kp.p_vm_tsize * pagesize;
memdata = (long)kp.p_vm_dsize * pagesize;
memstack = (long)kp.p_vm_ssize * pagesize;
#endif
#ifdef PSUTIL_FREEBSD
// what CPU we're on; top was used as an example:
// https://svnweb.freebsd.org/base/head/usr.bin/top/machine.c?
// view=markup&pathrev=273835
// XXX - note: for "intr" PID this is -1.
if (kp.ki_stat == SRUN && kp.ki_oncpu != NOCPU)
oncpu = kp.ki_oncpu;
else
oncpu = kp.ki_lastcpu;
#else
// On Net/OpenBSD we have kp.p_cpuid but it appears it's always
// set to KI_NOCPU. Even if it's not, ki_lastcpu does not exist
// so there's no way to determine where "sleeping" processes
// were. Not supported.
oncpu = -1;
#endif
#ifdef PSUTIL_FREEBSD
py_ppid = PyLong_FromPid(kp.ki_ppid);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
py_ppid = PyLong_FromPid(kp.p_ppid);
#else
py_ppid = Py_BuildfValue(-1);
#endif
if (! py_ppid)
return NULL;
// Return a single big tuple with all process info.
py_retlist = Py_BuildValue(
#if defined(__FreeBSD_version) && __FreeBSD_version >= 1200031
"(OillllllLdllllddddlllllbO)",
#else
"(OillllllidllllddddlllllbO)",
#endif
#ifdef PSUTIL_FREEBSD
py_ppid, // (pid_t) ppid
(int)kp.ki_stat, // (int) status
// UIDs
(long)kp.ki_ruid, // (long) real uid
(long)kp.ki_uid, // (long) effective uid
(long)kp.ki_svuid, // (long) saved uid
// GIDs
(long)kp.ki_rgid, // (long) real gid
(long)kp.ki_groups[0], // (long) effective gid
(long)kp.ki_svuid, // (long) saved gid
//
kp.ki_tdev, // (int or long long) tty nr
PSUTIL_TV2DOUBLE(kp.ki_start), // (double) create time
// ctx switches
kp.ki_rusage.ru_nvcsw, // (long) ctx switches (voluntary)
kp.ki_rusage.ru_nivcsw, // (long) ctx switches (unvoluntary)
// IO count
kp.ki_rusage.ru_inblock, // (long) read io count
kp.ki_rusage.ru_oublock, // (long) write io count
// CPU times: convert from micro seconds to seconds.
PSUTIL_TV2DOUBLE(kp.ki_rusage.ru_utime), // (double) user time
PSUTIL_TV2DOUBLE(kp.ki_rusage.ru_stime), // (double) sys time
PSUTIL_TV2DOUBLE(kp.ki_rusage_ch.ru_utime), // (double) children utime
PSUTIL_TV2DOUBLE(kp.ki_rusage_ch.ru_stime), // (double) children stime
// memory
rss, // (long) rss
vms, // (long) vms
memtext, // (long) mem text
memdata, // (long) mem data
memstack, // (long) mem stack
// others
oncpu, // (int) the CPU we are on
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
py_ppid, // (pid_t) ppid
(int)kp.p_stat, // (int) status
// UIDs
(long)kp.p_ruid, // (long) real uid
(long)kp.p_uid, // (long) effective uid
(long)kp.p_svuid, // (long) saved uid
// GIDs
(long)kp.p_rgid, // (long) real gid
(long)kp.p_groups[0], // (long) effective gid
(long)kp.p_svuid, // (long) saved gid
//
kp.p_tdev, // (int) tty nr
PSUTIL_KPT2DOUBLE(kp.p_ustart), // (double) create time
// ctx switches
kp.p_uru_nvcsw, // (long) ctx switches (voluntary)
kp.p_uru_nivcsw, // (long) ctx switches (unvoluntary)
// IO count
kp.p_uru_inblock, // (long) read io count
kp.p_uru_oublock, // (long) write io count
// CPU times: convert from micro seconds to seconds.
PSUTIL_KPT2DOUBLE(kp.p_uutime), // (double) user time
PSUTIL_KPT2DOUBLE(kp.p_ustime), // (double) sys time
// OpenBSD and NetBSD provide children user + system times summed
// together (no distinction).
kp.p_uctime_sec + kp.p_uctime_usec / 1000000.0, // (double) ch utime
kp.p_uctime_sec + kp.p_uctime_usec / 1000000.0, // (double) ch stime
// memory
rss, // (long) rss
vms, // (long) vms
memtext, // (long) mem text
memdata, // (long) mem data
memstack, // (long) mem stack
// others
oncpu, // (int) the CPU we are on
#endif
py_name // (pystr) name
);
Py_DECREF(py_name);
Py_DECREF(py_ppid);
return py_retlist;
}
PyObject *
psutil_proc_name(PyObject *self, PyObject *args) {
pid_t pid;
kinfo_proc kp;
char str[1000];
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
#ifdef PSUTIL_FREEBSD
sprintf(str, "%s", kp.ki_comm);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
sprintf(str, "%s", kp.p_comm);
#endif
return PyUnicode_DecodeFSDefault(str);
}
PyObject *
psutil_proc_environ(PyObject *self, PyObject *args) {
int i, cnt = -1;
long pid;
char *s, **envs, errbuf[_POSIX2_LINE_MAX];
PyObject *py_value=NULL, *py_retdict=NULL;
kvm_t *kd;
#ifdef PSUTIL_NETBSD
struct kinfo_proc2 *p;
#else
struct kinfo_proc *p;
#endif
if (!PyArg_ParseTuple(args, "l", &pid))
return NULL;
#if defined(PSUTIL_FREEBSD)
kd = kvm_openfiles(NULL, "/dev/null", NULL, 0, errbuf);
#else
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
#endif
if (!kd) {
convert_kvm_err("kvm_openfiles", errbuf);
return NULL;
}
py_retdict = PyDict_New();
if (!py_retdict)
goto error;
#if defined(PSUTIL_FREEBSD)
p = kvm_getprocs(kd, KERN_PROC_PID, pid, &cnt);
#elif defined(PSUTIL_OPENBSD)
p = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(*p), &cnt);
#elif defined(PSUTIL_NETBSD)
p = kvm_getproc2(kd, KERN_PROC_PID, pid, sizeof(*p), &cnt);
#endif
if (!p) {
NoSuchProcess("kvm_getprocs");
goto error;
}
if (cnt <= 0) {
NoSuchProcess(cnt < 0 ? kvm_geterr(kd) : "kvm_getprocs: cnt==0");
goto error;
}
// On *BSD kernels there are a few kernel-only system processes without an
// environment (See e.g. "procstat -e 0 | 1 | 2 ..." on FreeBSD.)
// Some system process have no stats attached at all
// (they are marked with P_SYSTEM.)
// On FreeBSD, it's possible that the process is swapped or paged out,
// then there no access to the environ stored in the process' user area.
// On NetBSD, we cannot call kvm_getenvv2() for a zombie process.
// To make unittest suite happy, return an empty environment.
#if defined(PSUTIL_FREEBSD)
#if (defined(__FreeBSD_version) && __FreeBSD_version >= 700000)
if (!((p)->ki_flag & P_INMEM) || ((p)->ki_flag & P_SYSTEM)) {
#else
if ((p)->ki_flag & P_SYSTEM) {
#endif
#elif defined(PSUTIL_NETBSD)
if ((p)->p_stat == SZOMB) {
#elif defined(PSUTIL_OPENBSD)
if ((p)->p_flag & P_SYSTEM) {
#endif
kvm_close(kd);
return py_retdict;
}
#if defined(PSUTIL_NETBSD)
envs = kvm_getenvv2(kd, p, 0);
#else
envs = kvm_getenvv(kd, p, 0);
#endif
if (!envs) {
// Map to "psutil" general high-level exceptions
switch (errno) {
case 0:
// Process has cleared it's environment, return empty one
kvm_close(kd);
return py_retdict;
case EPERM:
AccessDenied("kvm_getenvv -> EPERM");
break;
case ESRCH:
NoSuchProcess("kvm_getenvv -> ESRCH");
break;
#if defined(PSUTIL_FREEBSD)
case ENOMEM:
// Unfortunately, under FreeBSD kvm_getenvv() returns
// failure for certain processes ( e.g. try
// "sudo procstat -e <pid of your XOrg server>".)
// Map the error condition to 'AccessDenied'.
sprintf(errbuf,
"kvm_getenvv(pid=%ld, ki_uid=%d) -> ENOMEM",
pid, p->ki_uid);
AccessDenied(errbuf);
break;
#endif
default:
sprintf(errbuf, "kvm_getenvv(pid=%ld)", pid);
PyErr_SetFromOSErrnoWithSyscall(errbuf);
break;
}
goto error;
}
for (i = 0; envs[i] != NULL; i++) {
s = strchr(envs[i], '=');
if (!s)
continue;
*s++ = 0;
py_value = PyUnicode_DecodeFSDefault(s);
if (!py_value)
goto error;
if (PyDict_SetItemString(py_retdict, envs[i], py_value)) {
goto error;
}
Py_DECREF(py_value);
}
kvm_close(kd);
return py_retdict;
error:
Py_XDECREF(py_value);
Py_XDECREF(py_retdict);
kvm_close(kd);
return NULL;
}
/*
* Return files opened by process as a list of (path, fd) tuples.
* TODO: this is broken as it may report empty paths. 'procstat'
* utility has the same problem see:
* https://github.com/giampaolo/psutil/issues/595
*/
#if (defined(__FreeBSD_version) && __FreeBSD_version >= 800000) || PSUTIL_OPENBSD || defined(PSUTIL_NETBSD)
PyObject *
psutil_proc_open_files(PyObject *self, PyObject *args) {
pid_t pid;
int i;
int cnt;
int regular;
int fd;
char *path;
struct kinfo_file *freep = NULL;
struct kinfo_file *kif;
kinfo_proc kipp;
PyObject *py_tuple = NULL;
PyObject *py_path = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
if (psutil_kinfo_proc(pid, &kipp) == -1)
goto error;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
#if !defined(PSUTIL_OPENBSD)
psutil_raise_for_pid(pid, "kinfo_getfile()");
#endif
goto error;
}
for (i = 0; i < cnt; i++) {
kif = &freep[i];
#ifdef PSUTIL_FREEBSD
regular = (kif->kf_type == KF_TYPE_VNODE) && \
(kif->kf_vnode_type == KF_VTYPE_VREG);
fd = kif->kf_fd;
path = kif->kf_path;
#elif PSUTIL_OPENBSD
regular = (kif->f_type == DTYPE_VNODE) && (kif->v_type == VREG);
fd = kif->fd_fd;
// XXX - it appears path is not exposed in the kinfo_file struct.
path = "";
#elif PSUTIL_NETBSD
regular = (kif->ki_ftype == DTYPE_VNODE) && (kif->ki_vtype == VREG);
fd = kif->ki_fd;
// XXX - it appears path is not exposed in the kinfo_file struct.
path = "";
#endif
if (regular == 1) {
py_path = PyUnicode_DecodeFSDefault(path);
if (! py_path)
goto error;
py_tuple = Py_BuildValue("(Oi)", py_path, fd);
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_path);
Py_CLEAR(py_tuple);
}
}
free(freep);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (freep != NULL)
free(freep);
return NULL;
}
#endif
| 15,817 | 30.955556 | 107 | c |
psutil | psutil-master/psutil/arch/bsd/proc.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_pids(PyObject *self, PyObject *args);
PyObject *psutil_proc_environ(PyObject *self, PyObject *args);
PyObject *psutil_proc_name(PyObject *self, PyObject *args);
PyObject *psutil_proc_oneshot_info(PyObject *self, PyObject *args);
PyObject *psutil_proc_open_files(PyObject *self, PyObject *args);
| 519 | 36.142857 | 73 | h |
psutil | psutil-master/psutil/arch/bsd/sys.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <sys/param.h> // OS version
#ifdef PSUTIL_FREEBSD
#if __FreeBSD_version < 900000
#include <utmp.h>
#else
#include <utmpx.h>
#endif
#elif PSUTIL_NETBSD
#include <utmpx.h>
#elif PSUTIL_OPENBSD
#include <utmp.h>
#endif
// Return a Python float indicating the system boot time expressed in
// seconds since the epoch.
PyObject *
psutil_boot_time(PyObject *self, PyObject *args) {
// fetch sysctl "kern.boottime"
static int request[2] = { CTL_KERN, KERN_BOOTTIME };
struct timeval boottime;
size_t len = sizeof(boottime);
if (sysctl(request, 2, &boottime, &len, NULL, 0) == -1)
return PyErr_SetFromErrno(PyExc_OSError);
return Py_BuildValue("d", (double)boottime.tv_sec);
}
PyObject *
psutil_users(PyObject *self, PyObject *args) {
PyObject *py_retlist = PyList_New(0);
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_tuple = NULL;
PyObject *py_pid = NULL;
if (py_retlist == NULL)
return NULL;
#if (defined(__FreeBSD_version) && (__FreeBSD_version < 900000)) || PSUTIL_OPENBSD
struct utmp ut;
FILE *fp;
Py_BEGIN_ALLOW_THREADS
fp = fopen(_PATH_UTMP, "r");
Py_END_ALLOW_THREADS
if (fp == NULL) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, _PATH_UTMP);
goto error;
}
while (fread(&ut, sizeof(ut), 1, fp) == 1) {
if (*ut.ut_name == '\0')
continue;
py_username = PyUnicode_DecodeFSDefault(ut.ut_name);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(ut.ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(ut.ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"(OOOdi)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)ut.ut_time, // start time
#if defined(PSUTIL_OPENBSD) || (defined(__FreeBSD_version) && __FreeBSD_version < 900000)
-1 // process id (set to None later)
#else
ut.ut_pid // TODO: use PyLong_FromPid
#endif
);
if (!py_tuple) {
fclose(fp);
goto error;
}
if (PyList_Append(py_retlist, py_tuple)) {
fclose(fp);
goto error;
}
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
}
fclose(fp);
#else
struct utmpx *utx;
setutxent();
while ((utx = getutxent()) != NULL) {
if (utx->ut_type != USER_PROCESS)
continue;
py_username = PyUnicode_DecodeFSDefault(utx->ut_user);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(utx->ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(utx->ut_host);
if (! py_hostname)
goto error;
#ifdef PSUTIL_OPENBSD
py_pid = Py_BuildValue("i", -1); // set to None later
#else
py_pid = PyLong_FromPid(utx->ut_pid);
#endif
if (! py_pid)
goto error;
py_tuple = Py_BuildValue(
"(OOOdO)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)utx->ut_tv.tv_sec, // start time
py_pid // process id
);
if (!py_tuple) {
endutxent();
goto error;
}
if (PyList_Append(py_retlist, py_tuple)) {
endutxent();
goto error;
}
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
Py_CLEAR(py_pid);
}
endutxent();
#endif
return py_retlist;
error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_XDECREF(py_pid);
Py_DECREF(py_retlist);
return NULL;
}
| 4,387 | 26.08642 | 89 | c |
psutil | psutil-master/psutil/arch/bsd/sys.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_boot_time(PyObject *self, PyObject *args);
PyObject *psutil_users(PyObject *self, PyObject *args);
| 323 | 28.454545 | 73 | h |
psutil | psutil-master/psutil/arch/freebsd/cpu.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
System-wide CPU related functions.
Original code was refactored and moved from psutil/arch/freebsd/specific.c
in 2020 (and was moved in there previously already) from cset.
a4c0a0eb0d2a872ab7a45e47fcf37ef1fde5b012
For reference, here's the git history with original(ish) implementations:
- CPU stats: fb0154ef164d0e5942ac85102ab660b8d2938fbb
- CPU freq: 459556dd1e2979cdee22177339ced0761caf4c83
- CPU cores: e0d6d7865df84dc9a1d123ae452fd311f79b1dde
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <devstat.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
static int maxcpus;
int mib[2];
int ncpu;
size_t len;
size_t size;
int i;
PyObject *py_retlist = PyList_New(0);
PyObject *py_cputime = NULL;
if (py_retlist == NULL)
return NULL;
// retrieve maxcpus value
size = sizeof(maxcpus);
if (sysctlbyname("kern.smp.maxcpus", &maxcpus, &size, NULL, 0) < 0) {
Py_DECREF(py_retlist);
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('kern.smp.maxcpus')");
}
long cpu_time[maxcpus][CPUSTATES];
// retrieve the number of cpus
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(HW_NCPU)");
goto error;
}
// per-cpu info
size = sizeof(cpu_time);
if (sysctlbyname("kern.cp_times", &cpu_time, &size, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctlbyname('kern.smp.maxcpus')");
goto error;
}
for (i = 0; i < ncpu; i++) {
py_cputime = Py_BuildValue(
"(ddddd)",
(double)cpu_time[i][CP_USER] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_NICE] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_SYS] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_IDLE] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_INTR] / CLOCKS_PER_SEC);
if (!py_cputime)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_DECREF(py_cputime);
}
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
return NULL;
}
PyObject *
psutil_cpu_topology(PyObject *self, PyObject *args) {
void *topology = NULL;
size_t size = 0;
PyObject *py_str;
if (sysctlbyname("kern.sched.topology_spec", NULL, &size, NULL, 0))
goto error;
topology = malloc(size);
if (!topology) {
PyErr_NoMemory();
return NULL;
}
if (sysctlbyname("kern.sched.topology_spec", topology, &size, NULL, 0))
goto error;
py_str = Py_BuildValue("s", topology);
free(topology);
return py_str;
error:
if (topology != NULL)
free(topology);
Py_RETURN_NONE;
}
PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
unsigned int v_soft;
unsigned int v_intr;
unsigned int v_syscall;
unsigned int v_trap;
unsigned int v_swtch;
size_t size = sizeof(v_soft);
if (sysctlbyname("vm.stats.sys.v_soft", &v_soft, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_soft')");
}
if (sysctlbyname("vm.stats.sys.v_intr", &v_intr, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_intr')");
}
if (sysctlbyname("vm.stats.sys.v_syscall", &v_syscall, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_syscall')");
}
if (sysctlbyname("vm.stats.sys.v_trap", &v_trap, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_trap')");
}
if (sysctlbyname("vm.stats.sys.v_swtch", &v_swtch, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_swtch')");
}
return Py_BuildValue(
"IIIII",
v_swtch, // ctx switches
v_intr, // interrupts
v_soft, // software interrupts
v_syscall, // syscalls
v_trap // traps
);
}
/*
* Return frequency information of a given CPU.
* As of Dec 2018 only CPU 0 appears to be supported and all other
* cores match the frequency of CPU 0.
*/
PyObject *
psutil_cpu_freq(PyObject *self, PyObject *args) {
int current;
int core;
char sensor[26];
char available_freq_levels[1000];
size_t size = sizeof(current);
if (! PyArg_ParseTuple(args, "i", &core))
return NULL;
// https://www.unix.com/man-page/FreeBSD/4/cpufreq/
sprintf(sensor, "dev.cpu.%d.freq", core);
if (sysctlbyname(sensor, ¤t, &size, NULL, 0))
goto error;
size = sizeof(available_freq_levels);
// https://www.unix.com/man-page/FreeBSD/4/cpufreq/
// In case of failure, an empty string is returned.
sprintf(sensor, "dev.cpu.%d.freq_levels", core);
sysctlbyname(sensor, &available_freq_levels, &size, NULL, 0);
return Py_BuildValue("is", current, available_freq_levels);
error:
if (errno == ENOENT)
PyErr_SetString(PyExc_NotImplementedError, "unable to read frequency");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
| 5,555 | 27.492308 | 79 | c |
psutil | psutil-master/psutil/arch/freebsd/cpu.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_cpu_freq(PyObject* self, PyObject* args);
PyObject *psutil_cpu_stats(PyObject* self, PyObject* args);
PyObject *psutil_cpu_topology(PyObject* self, PyObject* args);
PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
| 453 | 33.923077 | 73 | h |
psutil | psutil-master/psutil/arch/freebsd/disk.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <devstat.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
// convert a bintime struct to milliseconds
#define PSUTIL_BT2MSEC(bt) (bt.sec * 1000 + (((uint64_t) 1000000000 * (uint32_t) \
(bt.frac >> 32) ) >> 32 ) / 1000000)
PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
int i;
struct statinfo stats;
PyObject *py_retdict = PyDict_New();
PyObject *py_disk_info = NULL;
if (py_retdict == NULL)
return NULL;
if (devstat_checkversion(NULL) < 0) {
PyErr_Format(PyExc_RuntimeError,
"devstat_checkversion() syscall failed");
goto error;
}
stats.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
if (stats.dinfo == NULL) {
PyErr_NoMemory();
goto error;
}
bzero(stats.dinfo, sizeof(struct devinfo));
if (devstat_getdevs(NULL, &stats) == -1) {
PyErr_Format(PyExc_RuntimeError, "devstat_getdevs() syscall failed");
goto error;
}
for (i = 0; i < stats.dinfo->numdevs; i++) {
py_disk_info = NULL;
struct devstat current;
char disk_name[128];
current = stats.dinfo->devices[i];
snprintf(disk_name, sizeof(disk_name), "%s%d",
current.device_name,
current.unit_number);
py_disk_info = Py_BuildValue(
"(KKKKLLL)",
current.operations[DEVSTAT_READ], // no reads
current.operations[DEVSTAT_WRITE], // no writes
current.bytes[DEVSTAT_READ], // bytes read
current.bytes[DEVSTAT_WRITE], // bytes written
(long long) PSUTIL_BT2MSEC(current.duration[DEVSTAT_READ]), // r time
(long long) PSUTIL_BT2MSEC(current.duration[DEVSTAT_WRITE]), // w time
(long long) PSUTIL_BT2MSEC(current.busy_time) // busy time
); // finished transactions
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, disk_name, py_disk_info))
goto error;
Py_DECREF(py_disk_info);
}
if (stats.dinfo->mem_ptr)
free(stats.dinfo->mem_ptr);
free(stats.dinfo);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (stats.dinfo != NULL)
free(stats.dinfo);
return NULL;
}
| 2,599 | 28.885057 | 83 | c |
psutil | psutil-master/psutil/arch/freebsd/disk.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_disk_io_counters(PyObject* self, PyObject* args);
| 274 | 26.5 | 73 | h |
psutil | psutil-master/psutil/arch/freebsd/mem.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <vm/vm_param.h>
#include <devstat.h>
#include <paths.h>
#include <fcntl.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#ifndef _PATH_DEVNULL
#define _PATH_DEVNULL "/dev/null"
#endif
PyObject *
psutil_virtual_mem(PyObject *self, PyObject *args) {
unsigned long total;
unsigned int active, inactive, wired, cached, free;
size_t size = sizeof(total);
struct vmtotal vm;
int mib[] = {CTL_VM, VM_METER};
long pagesize = psutil_getpagesize();
#if __FreeBSD_version > 702101
long buffers;
#else
int buffers;
#endif
size_t buffers_size = sizeof(buffers);
if (sysctlbyname("hw.physmem", &total, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall("sysctlbyname('hw.physmem')");
}
if (sysctlbyname("vm.stats.vm.v_active_count", &active, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_active_count')");
}
if (sysctlbyname("vm.stats.vm.v_inactive_count", &inactive, &size, NULL, 0))
{
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_inactive_count')");
}
if (sysctlbyname("vm.stats.vm.v_wire_count", &wired, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_wire_count')");
}
// https://github.com/giampaolo/psutil/issues/997
if (sysctlbyname("vm.stats.vm.v_cache_count", &cached, &size, NULL, 0)) {
cached = 0;
}
if (sysctlbyname("vm.stats.vm.v_free_count", &free, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_free_count')");
}
if (sysctlbyname("vfs.bufspace", &buffers, &buffers_size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall("sysctlbyname('vfs.bufspace')");
}
size = sizeof(vm);
if (sysctl(mib, 2, &vm, &size, NULL, 0) != 0) {
return PyErr_SetFromOSErrnoWithSyscall("sysctl(CTL_VM | VM_METER)");
}
return Py_BuildValue("KKKKKKKK",
(unsigned long long) total,
(unsigned long long) free * pagesize,
(unsigned long long) active * pagesize,
(unsigned long long) inactive * pagesize,
(unsigned long long) wired * pagesize,
(unsigned long long) cached * pagesize,
(unsigned long long) buffers,
(unsigned long long) (vm.t_vmshr + vm.t_rmshr) * pagesize // shared
);
}
PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
// Return swap memory stats (see 'swapinfo' cmdline tool)
kvm_t *kd;
struct kvm_swap kvmsw[1];
unsigned int swapin, swapout, nodein, nodeout;
size_t size = sizeof(unsigned int);
long pagesize = psutil_getpagesize();
kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open failed");
if (kd == NULL) {
PyErr_SetString(PyExc_RuntimeError, "kvm_open() syscall failed");
return NULL;
}
if (kvm_getswapinfo(kd, kvmsw, 1, 0) < 0) {
kvm_close(kd);
PyErr_SetString(PyExc_RuntimeError,
"kvm_getswapinfo() syscall failed");
return NULL;
}
kvm_close(kd);
if (sysctlbyname("vm.stats.vm.v_swapin", &swapin, &size, NULL, 0) == -1) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_swapin)'");
}
if (sysctlbyname("vm.stats.vm.v_swapout", &swapout, &size, NULL, 0) == -1){
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_swapout)'");
}
if (sysctlbyname("vm.stats.vm.v_vnodein", &nodein, &size, NULL, 0) == -1) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_vnodein)'");
}
if (sysctlbyname("vm.stats.vm.v_vnodeout", &nodeout, &size, NULL, 0) == -1) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_vnodeout)'");
}
return Py_BuildValue(
"(KKKII)",
(unsigned long long)kvmsw[0].ksw_total * pagesize, // total
(unsigned long long)kvmsw[0].ksw_used * pagesize, // used
(unsigned long long)kvmsw[0].ksw_total * pagesize - // free
kvmsw[0].ksw_used * pagesize,
swapin + swapout, // swap in
nodein + nodeout // swap out
);
}
| 4,652 | 32.47482 | 81 | c |
psutil | psutil-master/psutil/arch/freebsd/mem.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_swap_mem(PyObject* self, PyObject* args);
PyObject *psutil_virtual_mem(PyObject* self, PyObject* args);
| 328 | 28.909091 | 73 | h |
psutil | psutil-master/psutil/arch/freebsd/proc.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/proc.h>
#include <signal.h>
#include <fcntl.h>
#include <devstat.h>
#include <libutil.h> // process open files, shared libs (kinfo_getvmmap), cwd
#include <sys/cpuset.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
// ============================================================================
// Utility functions
// ============================================================================
int
psutil_kinfo_proc(pid_t pid, struct kinfo_proc *proc) {
// Fills a kinfo_proc struct based on process pid.
int mib[4];
size_t size;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = pid;
size = sizeof(struct kinfo_proc);
if (sysctl((int *)mib, 4, proc, &size, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_PID)");
return -1;
}
// sysctl stores 0 in the size if we can't find the process information.
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
return -1;
}
return 0;
}
// remove spaces from string
static void psutil_remove_spaces(char *str) {
char *p1 = str;
char *p2 = str;
do
while (*p2 == ' ')
p2++;
while ((*p1++ = *p2++));
}
// ============================================================================
// APIS
// ============================================================================
int
psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount) {
// Returns a list of all BSD processes on the system. This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount. You are responsible for freeing
// this list. On success returns 0, else 1 with exception set.
int err;
struct kinfo_proc *buf = NULL;
int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0 };
size_t length = 0;
size_t max_length = 12 * 1024 * 1024; // 12MB
assert(procList != NULL);
assert(*procList == NULL);
assert(procCount != NULL);
// Call sysctl with a NULL buffer in order to get buffer length.
err = sysctl(name, 3, NULL, &length, NULL, 0);
if (err == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl (null buffer)");
return 1;
}
while (1) {
// Allocate an appropriately sized buffer based on the results
// from the previous call.
buf = malloc(length);
if (buf == NULL) {
PyErr_NoMemory();
return 1;
}
// Call sysctl again with the new buffer.
err = sysctl(name, 3, buf, &length, NULL, 0);
if (err == -1) {
free(buf);
if (errno == ENOMEM) {
// Sometimes the first sysctl() suggested size is not enough,
// so we dynamically increase it until it's big enough :
// https://github.com/giampaolo/psutil/issues/2093
psutil_debug("errno=ENOMEM, length=%zu; retrying", length);
length *= 2;
if (length < max_length) {
continue;
}
}
PyErr_SetFromOSErrnoWithSyscall("sysctl()");
return 1;
}
else {
break;
}
}
*procList = buf;
*procCount = length / sizeof(struct kinfo_proc);
return 0;
}
/*
* Borrowed from psi Python System Information project
* Based on code from ps.
*/
PyObject *
psutil_proc_cmdline(PyObject *self, PyObject *args) {
pid_t pid;
int mib[4];
int argmax;
size_t size = sizeof(argmax);
char *procargs = NULL;
size_t pos = 0;
PyObject *py_retlist = PyList_New(0);
PyObject *py_arg = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
// Get the maximum process arguments size.
mib[0] = CTL_KERN;
mib[1] = KERN_ARGMAX;
size = sizeof(argmax);
if (sysctl(mib, 2, &argmax, &size, NULL, 0) == -1)
goto error;
// Allocate space for the arguments.
procargs = (char *)malloc(argmax);
if (procargs == NULL) {
PyErr_NoMemory();
goto error;
}
// Make a sysctl() call to get the raw argument space of the process.
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_ARGS;
mib[3] = pid;
size = argmax;
if (sysctl(mib, 4, procargs, &size, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ARGS)");
goto error;
}
// args are returned as a flattened string with \0 separators between
// arguments add each string to the list then step forward to the next
// separator
if (size > 0) {
while (pos < size) {
py_arg = PyUnicode_DecodeFSDefault(&procargs[pos]);
if (!py_arg)
goto error;
if (PyList_Append(py_retlist, py_arg))
goto error;
Py_DECREF(py_arg);
pos = pos + strlen(&procargs[pos]) + 1;
}
}
free(procargs);
return py_retlist;
error:
Py_XDECREF(py_arg);
Py_DECREF(py_retlist);
if (procargs != NULL)
free(procargs);
return NULL;
}
/*
* Return process pathname executable.
* Thanks to Robert N. M. Watson:
* http://fxr.googlebit.com/source/usr.bin/procstat/procstat_bin.c?v=8-CURRENT
*/
PyObject *
psutil_proc_exe(PyObject *self, PyObject *args) {
pid_t pid;
char pathname[PATH_MAX];
int error;
int mib[4];
int ret;
size_t size;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = pid;
size = sizeof(pathname);
error = sysctl(mib, 4, pathname, &size, NULL, 0);
if (error == -1) {
// see: https://github.com/giampaolo/psutil/issues/907
if (errno == ENOENT) {
return PyUnicode_DecodeFSDefault("");
}
else {
return \
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_PATHNAME)");
}
}
if (size == 0 || strlen(pathname) == 0) {
ret = psutil_pid_exists(pid);
if (ret == -1)
return NULL;
else if (ret == 0)
return NoSuchProcess("psutil_pid_exists -> 0");
else
strcpy(pathname, "");
}
return PyUnicode_DecodeFSDefault(pathname);
}
PyObject *
psutil_proc_num_threads(PyObject *self, PyObject *args) {
// Return number of threads used by process as a Python integer.
pid_t pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
return Py_BuildValue("l", (long)kp.ki_numthreads);
}
PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
// Retrieves all threads used by process returning a list of tuples
// including thread id, user time and system time.
// Thanks to Robert N. M. Watson:
// http://code.metager.de/source/xref/freebsd/usr.bin/procstat/
// procstat_threads.c
pid_t pid;
int mib[4];
struct kinfo_proc *kip = NULL;
struct kinfo_proc *kipp = NULL;
int error;
unsigned int i;
size_t size;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
// we need to re-query for thread information, so don't use *kipp
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID | KERN_PROC_INC_THREAD;
mib[3] = pid;
size = 0;
error = sysctl(mib, 4, NULL, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_INC_THREAD)");
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
kip = malloc(size);
if (kip == NULL) {
PyErr_NoMemory();
goto error;
}
error = sysctl(mib, 4, kip, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_INC_THREAD)");
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
for (i = 0; i < size / sizeof(*kipp); i++) {
kipp = &kip[i];
py_tuple = Py_BuildValue("Idd",
kipp->ki_tid,
PSUTIL_TV2DOUBLE(kipp->ki_rusage.ru_utime),
PSUTIL_TV2DOUBLE(kipp->ki_rusage.ru_stime));
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
free(kip);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (kip != NULL)
free(kip);
return NULL;
}
#if defined(__FreeBSD_version) && __FreeBSD_version >= 701000
PyObject *
psutil_proc_cwd(PyObject *self, PyObject *args) {
pid_t pid;
struct kinfo_file *freep = NULL;
struct kinfo_file *kif;
struct kinfo_proc kipp;
PyObject *py_path = NULL;
int i, cnt;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
if (psutil_kinfo_proc(pid, &kipp) == -1)
goto error;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
goto error;
}
for (i = 0; i < cnt; i++) {
kif = &freep[i];
if (kif->kf_fd == KF_FD_TYPE_CWD) {
py_path = PyUnicode_DecodeFSDefault(kif->kf_path);
if (!py_path)
goto error;
break;
}
}
/*
* For lower pids it seems we can't retrieve any information
* (lsof can't do that it either). Since this happens even
* as root we return an empty string instead of AccessDenied.
*/
if (py_path == NULL)
py_path = PyUnicode_DecodeFSDefault("");
free(freep);
return py_path;
error:
Py_XDECREF(py_path);
if (freep != NULL)
free(freep);
return NULL;
}
#endif
#if defined(__FreeBSD_version) && __FreeBSD_version >= 800000
PyObject *
psutil_proc_num_fds(PyObject *self, PyObject *args) {
pid_t pid;
int cnt;
struct kinfo_file *freep;
struct kinfo_proc kipp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kipp) == -1)
return NULL;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
return NULL;
}
free(freep);
return Py_BuildValue("i", cnt);
}
#endif
PyObject *
psutil_proc_memory_maps(PyObject *self, PyObject *args) {
// Return a list of tuples for every process memory maps.
// 'procstat' cmdline utility has been used as an example.
pid_t pid;
int ptrwidth;
int i, cnt;
char addr[1000];
char perms[4];
char *path;
struct kinfo_proc kp;
struct kinfo_vmentry *freep = NULL;
struct kinfo_vmentry *kve;
ptrwidth = 2 * sizeof(void *);
PyObject *py_tuple = NULL;
PyObject *py_path = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
if (psutil_kinfo_proc(pid, &kp) == -1)
goto error;
errno = 0;
freep = kinfo_getvmmap(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getvmmap()");
goto error;
}
for (i = 0; i < cnt; i++) {
py_tuple = NULL;
kve = &freep[i];
addr[0] = '\0';
perms[0] = '\0';
sprintf(addr, "%#*jx-%#*jx", ptrwidth, (uintmax_t)kve->kve_start,
ptrwidth, (uintmax_t)kve->kve_end);
psutil_remove_spaces(addr);
strlcat(perms, kve->kve_protection & KVME_PROT_READ ? "r" : "-",
sizeof(perms));
strlcat(perms, kve->kve_protection & KVME_PROT_WRITE ? "w" : "-",
sizeof(perms));
strlcat(perms, kve->kve_protection & KVME_PROT_EXEC ? "x" : "-",
sizeof(perms));
if (strlen(kve->kve_path) == 0) {
switch (kve->kve_type) {
case KVME_TYPE_NONE:
path = "[none]";
break;
case KVME_TYPE_DEFAULT:
path = "[default]";
break;
case KVME_TYPE_VNODE:
path = "[vnode]";
break;
case KVME_TYPE_SWAP:
path = "[swap]";
break;
case KVME_TYPE_DEVICE:
path = "[device]";
break;
case KVME_TYPE_PHYS:
path = "[phys]";
break;
case KVME_TYPE_DEAD:
path = "[dead]";
break;
#ifdef KVME_TYPE_SG
case KVME_TYPE_SG:
path = "[sg]";
break;
#endif
case KVME_TYPE_UNKNOWN:
path = "[unknown]";
break;
default:
path = "[?]";
break;
}
}
else {
path = kve->kve_path;
}
py_path = PyUnicode_DecodeFSDefault(path);
if (! py_path)
goto error;
py_tuple = Py_BuildValue("ssOiiii",
addr, // "start-end" address
perms, // "rwx" permissions
py_path, // path
kve->kve_resident, // rss
kve->kve_private_resident, // private
kve->kve_ref_count, // ref count
kve->kve_shadow_count); // shadow count
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_path);
Py_DECREF(py_tuple);
}
free(freep);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_path);
Py_DECREF(py_retlist);
if (freep != NULL)
free(freep);
return NULL;
}
PyObject*
psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args) {
// Get process CPU affinity.
// Reference:
// http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
pid_t pid;
int ret;
int i;
cpuset_t mask;
PyObject* py_retlist;
PyObject* py_cpu_num;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
ret = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
sizeof(mask), &mask);
if (ret != 0)
return PyErr_SetFromErrno(PyExc_OSError);
py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
for (i = 0; i < CPU_SETSIZE; i++) {
if (CPU_ISSET(i, &mask)) {
py_cpu_num = Py_BuildValue("i", i);
if (py_cpu_num == NULL)
goto error;
if (PyList_Append(py_retlist, py_cpu_num))
goto error;
}
}
return py_retlist;
error:
Py_XDECREF(py_cpu_num);
Py_DECREF(py_retlist);
return NULL;
}
PyObject *
psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
// Set process CPU affinity.
// Reference:
// http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
pid_t pid;
int i;
int seq_len;
int ret;
cpuset_t cpu_set;
PyObject *py_cpu_set;
PyObject *py_cpu_seq = NULL;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &py_cpu_set))
return NULL;
py_cpu_seq = PySequence_Fast(py_cpu_set, "expected a sequence or integer");
if (!py_cpu_seq)
return NULL;
seq_len = PySequence_Fast_GET_SIZE(py_cpu_seq);
// calculate the mask
CPU_ZERO(&cpu_set);
for (i = 0; i < seq_len; i++) {
PyObject *item = PySequence_Fast_GET_ITEM(py_cpu_seq, i);
#if PY_MAJOR_VERSION >= 3
long value = PyLong_AsLong(item);
#else
long value = PyInt_AsLong(item);
#endif
if (value == -1 || PyErr_Occurred())
goto error;
CPU_SET(value, &cpu_set);
}
// set affinity
ret = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
sizeof(cpu_set), &cpu_set);
if (ret != 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
Py_DECREF(py_cpu_seq);
Py_RETURN_NONE;
error:
if (py_cpu_seq != NULL)
Py_DECREF(py_cpu_seq);
return NULL;
}
/*
* An emulation of Linux prlimit(). Returns a (soft, hard) tuple.
*/
PyObject *
psutil_proc_getrlimit(PyObject *self, PyObject *args) {
pid_t pid;
int ret;
int resource;
size_t len;
int name[5];
struct rlimit rlp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &resource))
return NULL;
name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_RLIMIT;
name[3] = pid;
name[4] = resource;
len = sizeof(rlp);
ret = sysctl(name, 5, &rlp, &len, NULL, 0);
if (ret == -1)
return PyErr_SetFromErrno(PyExc_OSError);
#if defined(HAVE_LONG_LONG)
return Py_BuildValue("LL",
(PY_LONG_LONG) rlp.rlim_cur,
(PY_LONG_LONG) rlp.rlim_max);
#else
return Py_BuildValue("ll",
(long) rlp.rlim_cur,
(long) rlp.rlim_max);
#endif
}
/*
* An emulation of Linux prlimit() (set).
*/
PyObject *
psutil_proc_setrlimit(PyObject *self, PyObject *args) {
pid_t pid;
int ret;
int resource;
int name[5];
struct rlimit new;
struct rlimit *newp = NULL;
PyObject *py_soft = NULL;
PyObject *py_hard = NULL;
if (! PyArg_ParseTuple(
args, _Py_PARSE_PID "iOO", &pid, &resource, &py_soft, &py_hard))
return NULL;
name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_RLIMIT;
name[3] = pid;
name[4] = resource;
#if defined(HAVE_LONG_LONG)
new.rlim_cur = PyLong_AsLongLong(py_soft);
if (new.rlim_cur == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
new.rlim_max = PyLong_AsLongLong(py_hard);
if (new.rlim_max == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
#else
new.rlim_cur = PyLong_AsLong(py_soft);
if (new.rlim_cur == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
new.rlim_max = PyLong_AsLong(py_hard);
if (new.rlim_max == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
#endif
newp = &new;
ret = sysctl(name, 5, NULL, 0, newp, sizeof(*newp));
if (ret == -1)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
}
| 19,437 | 25.848066 | 79 | c |
psutil | psutil-master/psutil/arch/freebsd/proc.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
typedef struct kinfo_proc kinfo_proc;
int psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount);
int psutil_kinfo_proc(const pid_t pid, struct kinfo_proc *proc);
PyObject* psutil_proc_cmdline(PyObject* self, PyObject* args);
PyObject* psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args);
PyObject* psutil_proc_cpu_affinity_set(PyObject* self, PyObject* args);
PyObject* psutil_proc_cwd(PyObject* self, PyObject* args);
PyObject* psutil_proc_exe(PyObject* self, PyObject* args);
PyObject* psutil_proc_getrlimit(PyObject* self, PyObject* args);
PyObject* psutil_proc_memory_maps(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_fds(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_threads(PyObject* self, PyObject* args);
PyObject* psutil_proc_setrlimit(PyObject* self, PyObject* args);
PyObject* psutil_proc_threads(PyObject* self, PyObject* args);
| 1,102 | 43.12 | 74 | h |
psutil | psutil-master/psutil/arch/freebsd/proc_socks.c | /*
* Copyright (c) 2009, Giampaolo Rodola'.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Retrieves per-process open socket connections.
*/
#include <Python.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/socketvar.h> // for struct xsocket
#include <sys/un.h>
#include <sys/sysctl.h>
#include <netinet/in.h> // for xinpcb struct
#include <netinet/in_pcb.h>
#include <netinet/tcp_var.h> // for struct xtcpcb
#include <arpa/inet.h> // for inet_ntop()
#include <libutil.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
// The tcplist fetching and walking is borrowed from netstat/inet.c.
static char *
psutil_fetch_tcplist(void) {
char *buf;
size_t len;
for (;;) {
if (sysctlbyname("net.inet.tcp.pcblist", NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
buf = malloc(len);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
if (sysctlbyname("net.inet.tcp.pcblist", buf, &len, NULL, 0) < 0) {
free(buf);
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return buf;
}
}
static int
psutil_sockaddr_port(int family, struct sockaddr_storage *ss) {
struct sockaddr_in6 *sin6;
struct sockaddr_in *sin;
if (family == AF_INET) {
sin = (struct sockaddr_in *)ss;
return (sin->sin_port);
}
else {
sin6 = (struct sockaddr_in6 *)ss;
return (sin6->sin6_port);
}
}
static void *
psutil_sockaddr_addr(int family, struct sockaddr_storage *ss) {
struct sockaddr_in6 *sin6;
struct sockaddr_in *sin;
if (family == AF_INET) {
sin = (struct sockaddr_in *)ss;
return (&sin->sin_addr);
}
else {
sin6 = (struct sockaddr_in6 *)ss;
return (&sin6->sin6_addr);
}
}
static socklen_t
psutil_sockaddr_addrlen(int family) {
if (family == AF_INET)
return (sizeof(struct in_addr));
else
return (sizeof(struct in6_addr));
}
static int
psutil_sockaddr_matches(int family, int port, void *pcb_addr,
struct sockaddr_storage *ss) {
if (psutil_sockaddr_port(family, ss) != port)
return (0);
return (memcmp(psutil_sockaddr_addr(family, ss), pcb_addr,
psutil_sockaddr_addrlen(family)) == 0);
}
#if __FreeBSD_version >= 1200026
static struct xtcpcb *
psutil_search_tcplist(char *buf, struct kinfo_file *kif) {
struct xtcpcb *tp;
struct xinpcb *inp;
#else
static struct tcpcb *
psutil_search_tcplist(char *buf, struct kinfo_file *kif) {
struct tcpcb *tp;
struct inpcb *inp;
#endif
struct xinpgen *xig, *oxig;
struct xsocket *so;
oxig = xig = (struct xinpgen *)buf;
for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
xig->xig_len > sizeof(struct xinpgen);
xig = (struct xinpgen *)((char *)xig + xig->xig_len)) {
#if __FreeBSD_version >= 1200026
tp = (struct xtcpcb *)xig;
inp = &tp->xt_inp;
so = &inp->xi_socket;
#else
tp = &((struct xtcpcb *)xig)->xt_tp;
inp = &((struct xtcpcb *)xig)->xt_inp;
so = &((struct xtcpcb *)xig)->xt_socket;
#endif
if (so->so_type != kif->kf_sock_type ||
so->xso_family != kif->kf_sock_domain ||
so->xso_protocol != kif->kf_sock_protocol)
continue;
if (kif->kf_sock_domain == AF_INET) {
if (!psutil_sockaddr_matches(
AF_INET, inp->inp_lport, &inp->inp_laddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local))
#else
&kif->kf_un.kf_sock.kf_sa_local))
#endif
continue;
if (!psutil_sockaddr_matches(
AF_INET, inp->inp_fport, &inp->inp_faddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer))
#else
&kif->kf_un.kf_sock.kf_sa_peer))
#endif
continue;
} else {
if (!psutil_sockaddr_matches(
AF_INET6, inp->inp_lport, &inp->in6p_laddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local))
#else
&kif->kf_un.kf_sock.kf_sa_local))
#endif
continue;
if (!psutil_sockaddr_matches(
AF_INET6, inp->inp_fport, &inp->in6p_faddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer))
#else
&kif->kf_un.kf_sock.kf_sa_peer))
#endif
continue;
}
return (tp);
}
return NULL;
}
PyObject *
psutil_proc_connections(PyObject *self, PyObject *args) {
// Return connections opened by process.
pid_t pid;
int i;
int cnt;
struct kinfo_file *freep = NULL;
struct kinfo_file *kif;
char *tcplist = NULL;
#if __FreeBSD_version >= 1200026
struct xtcpcb *tcp;
#else
struct tcpcb *tcp;
#endif
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
PyObject *py_af_filter = NULL;
PyObject *py_type_filter = NULL;
PyObject *py_family = NULL;
PyObject *py_type = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID "OO", &pid,
&py_af_filter, &py_type_filter))
{
goto error;
}
if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) {
PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
goto error;
}
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
goto error;
}
tcplist = psutil_fetch_tcplist();
if (tcplist == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < cnt; i++) {
int lport, rport, state;
char lip[200], rip[200];
char path[PATH_MAX];
int inseq;
py_tuple = NULL;
py_laddr = NULL;
py_raddr = NULL;
kif = &freep[i];
if (kif->kf_type == KF_TYPE_SOCKET) {
// apply filters
py_family = PyLong_FromLong((long)kif->kf_sock_domain);
inseq = PySequence_Contains(py_af_filter, py_family);
Py_DECREF(py_family);
if (inseq == 0)
continue;
py_type = PyLong_FromLong((long)kif->kf_sock_type);
inseq = PySequence_Contains(py_type_filter, py_type);
Py_DECREF(py_type);
if (inseq == 0)
continue;
// IPv4 / IPv6 socket
if ((kif->kf_sock_domain == AF_INET) ||
(kif->kf_sock_domain == AF_INET6)) {
// fill status
state = PSUTIL_CONN_NONE;
if (kif->kf_sock_type == SOCK_STREAM) {
tcp = psutil_search_tcplist(tcplist, kif);
if (tcp != NULL)
state = (int)tcp->t_state;
}
// build addr and port
inet_ntop(
kif->kf_sock_domain,
psutil_sockaddr_addr(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local),
#else
&kif->kf_un.kf_sock.kf_sa_local),
#endif
lip,
sizeof(lip));
inet_ntop(
kif->kf_sock_domain,
psutil_sockaddr_addr(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer),
#else
&kif->kf_un.kf_sock.kf_sa_peer),
#endif
rip,
sizeof(rip));
lport = htons(psutil_sockaddr_port(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local));
#else
&kif->kf_un.kf_sock.kf_sa_local));
#endif
rport = htons(psutil_sockaddr_port(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer));
#else
&kif->kf_un.kf_sock.kf_sa_peer));
#endif
// construct python tuple/list
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", rip, rport);
else
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
py_tuple = Py_BuildValue(
"(iiiNNi)",
kif->kf_fd,
kif->kf_sock_domain,
kif->kf_sock_type,
py_laddr,
py_raddr,
state
);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
// UNIX socket.
// Note: remote path cannot be determined.
else if (kif->kf_sock_domain == AF_UNIX) {
struct sockaddr_un *sun;
#if __FreeBSD_version < 1200031
sun = (struct sockaddr_un *)&kif->kf_sa_local;
#else
sun = (struct sockaddr_un *)&kif->kf_un.kf_sock.kf_sa_local;
#endif
snprintf(
path, sizeof(path), "%.*s",
(int)(sun->sun_len - (sizeof(*sun) - sizeof(sun->sun_path))),
sun->sun_path);
py_laddr = PyUnicode_DecodeFSDefault(path);
if (! py_laddr)
goto error;
py_tuple = Py_BuildValue(
"(iiiOsi)",
kif->kf_fd,
kif->kf_sock_domain,
kif->kf_sock_type,
py_laddr,
"", // raddr can't be determined
PSUTIL_CONN_NONE
);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
Py_DECREF(py_laddr);
}
}
}
free(freep);
free(tcplist);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
Py_DECREF(py_retlist);
if (freep != NULL)
free(freep);
if (tcplist != NULL)
free(tcplist);
return NULL;
}
| 11,001 | 28.495979 | 85 | c |
psutil | psutil-master/psutil/arch/freebsd/proc_socks.h | /*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject* psutil_proc_connections(PyObject* self, PyObject* args);
| 263 | 25.4 | 73 | h |
psutil | psutil-master/psutil/arch/freebsd/sensors.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
Original code was refactored and moved from psutil/arch/freebsd/specific.c
For reference, here's the git history with original(ish) implementations:
- sensors_battery(): 022cf0a05d34f4274269d4f8002ee95b9f3e32d2
- sensors_cpu_temperature(): bb5d032be76980a9e110f03f1203bd35fa85a793
(patch by Alex Manuskin)
*/
#include <Python.h>
#include <sys/sysctl.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#define DECIKELVIN_2_CELSIUS(t) (t - 2731) / 10
PyObject *
psutil_sensors_battery(PyObject *self, PyObject *args) {
int percent;
int minsleft;
int power_plugged;
size_t size = sizeof(percent);
if (sysctlbyname("hw.acpi.battery.life", &percent, &size, NULL, 0))
goto error;
if (sysctlbyname("hw.acpi.battery.time", &minsleft, &size, NULL, 0))
goto error;
if (sysctlbyname("hw.acpi.acline", &power_plugged, &size, NULL, 0))
goto error;
return Py_BuildValue("iii", percent, minsleft, power_plugged);
error:
// see: https://github.com/giampaolo/psutil/issues/1074
if (errno == ENOENT)
PyErr_SetString(PyExc_NotImplementedError, "no battery");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
// Return temperature information for a given CPU core number.
PyObject *
psutil_sensors_cpu_temperature(PyObject *self, PyObject *args) {
int current;
int tjmax;
int core;
char sensor[26];
size_t size = sizeof(current);
if (! PyArg_ParseTuple(args, "i", &core))
return NULL;
sprintf(sensor, "dev.cpu.%d.temperature", core);
if (sysctlbyname(sensor, ¤t, &size, NULL, 0))
goto error;
current = DECIKELVIN_2_CELSIUS(current);
// Return -273 in case of failure.
sprintf(sensor, "dev.cpu.%d.coretemp.tjmax", core);
if (sysctlbyname(sensor, &tjmax, &size, NULL, 0))
tjmax = 0;
tjmax = DECIKELVIN_2_CELSIUS(tjmax);
return Py_BuildValue("ii", current, tjmax);
error:
if (errno == ENOENT)
PyErr_SetString(PyExc_NotImplementedError, "no temperature sensors");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
| 2,329 | 27.072289 | 77 | c |
psutil | psutil-master/psutil/arch/freebsd/sensors.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject* psutil_sensors_battery(PyObject* self, PyObject* args);
PyObject* psutil_sensors_cpu_temperature(PyObject* self, PyObject* args);
| 347 | 30.636364 | 73 | h |
psutil | psutil-master/psutil/arch/freebsd/sys_socks.c | /*
* Copyright (c) 2009, Giampaolo Rodola'.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Retrieves system-wide open socket connections. This is based off of
* sockstat utility source code:
* https://github.com/freebsd/freebsd/blob/master/usr.bin/sockstat/sockstat.c
*/
#include <Python.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/file.h>
#include <sys/socketvar.h> // for struct xsocket
#include <sys/un.h>
#include <sys/unpcb.h>
#include <sys/sysctl.h>
#if defined(__FreeBSD_version) && __FreeBSD_version < 800000
#include <netinet/in_systm.h>
#endif
#include <netinet/in.h> // for xinpcb struct
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/tcp_var.h> // for struct xtcpcb
#include <arpa/inet.h> // for inet_ntop()
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
static struct xfile *psutil_xfiles;
static int psutil_nxfiles;
int
psutil_populate_xfiles(void) {
size_t len;
if ((psutil_xfiles = malloc(len = sizeof *psutil_xfiles)) == NULL) {
PyErr_NoMemory();
return 0;
}
while (sysctlbyname("kern.file", psutil_xfiles, &len, 0, 0) == -1) {
if (errno != ENOMEM) {
PyErr_SetFromErrno(0);
return 0;
}
len *= 2;
if ((psutil_xfiles = realloc(psutil_xfiles, len)) == NULL) {
PyErr_NoMemory();
return 0;
}
}
if (len > 0 && psutil_xfiles->xf_size != sizeof *psutil_xfiles) {
PyErr_Format(PyExc_RuntimeError, "struct xfile size mismatch");
return 0;
}
psutil_nxfiles = len / sizeof *psutil_xfiles;
return 1;
}
struct xfile *
psutil_get_file_from_sock(kvaddr_t sock) {
struct xfile *xf;
int n;
for (xf = psutil_xfiles, n = 0; n < psutil_nxfiles; ++n, ++xf) {
if (xf->xf_data == sock)
return xf;
}
return NULL;
}
// Reference:
// https://github.com/freebsd/freebsd/blob/master/usr.bin/sockstat/sockstat.c
int psutil_gather_inet(int proto, PyObject *py_retlist) {
struct xinpgen *xig, *exig;
struct xinpcb *xip;
struct xtcpcb *xtp;
#if __FreeBSD_version >= 1200026
struct xinpcb *inp;
#else
struct inpcb *inp;
#endif
struct xsocket *so;
const char *varname = NULL;
size_t len, bufsize;
void *buf;
int retry;
int type;
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
switch (proto) {
case IPPROTO_TCP:
varname = "net.inet.tcp.pcblist";
type = SOCK_STREAM;
break;
case IPPROTO_UDP:
varname = "net.inet.udp.pcblist";
type = SOCK_DGRAM;
break;
}
buf = NULL;
bufsize = 8192;
retry = 5;
do {
for (;;) {
buf = realloc(buf, bufsize);
if (buf == NULL)
continue; // XXX
len = bufsize;
if (sysctlbyname(varname, buf, &len, NULL, 0) == 0)
break;
if (errno != ENOMEM) {
PyErr_SetFromErrno(0);
goto error;
}
bufsize *= 2;
}
xig = (struct xinpgen *)buf;
exig = (struct xinpgen *)(void *)((char *)buf + len - sizeof *exig);
if (xig->xig_len != sizeof *xig || exig->xig_len != sizeof *exig) {
PyErr_Format(PyExc_RuntimeError, "struct xinpgen size mismatch");
goto error;
}
} while (xig->xig_gen != exig->xig_gen && retry--);
for (;;) {
struct xfile *xf;
int lport, rport, status, family;
xig = (struct xinpgen *)(void *)((char *)xig + xig->xig_len);
if (xig >= exig)
break;
switch (proto) {
case IPPROTO_TCP:
xtp = (struct xtcpcb *)xig;
if (xtp->xt_len != sizeof *xtp) {
PyErr_Format(PyExc_RuntimeError,
"struct xtcpcb size mismatch");
goto error;
}
inp = &xtp->xt_inp;
#if __FreeBSD_version >= 1200026
so = &inp->xi_socket;
status = xtp->t_state;
#else
so = &xtp->xt_socket;
status = xtp->xt_tp.t_state;
#endif
break;
case IPPROTO_UDP:
xip = (struct xinpcb *)xig;
if (xip->xi_len != sizeof *xip) {
PyErr_Format(PyExc_RuntimeError,
"struct xinpcb size mismatch");
goto error;
}
#if __FreeBSD_version >= 1200026
inp = xip;
#else
inp = &xip->xi_inp;
#endif
so = &xip->xi_socket;
status = PSUTIL_CONN_NONE;
break;
default:
PyErr_Format(PyExc_RuntimeError, "invalid proto");
goto error;
}
char lip[200], rip[200];
xf = psutil_get_file_from_sock(so->xso_so);
if (xf == NULL)
continue;
lport = ntohs(inp->inp_lport);
rport = ntohs(inp->inp_fport);
if (inp->inp_vflag & INP_IPV4) {
family = AF_INET;
inet_ntop(AF_INET, &inp->inp_laddr.s_addr, lip, sizeof(lip));
inet_ntop(AF_INET, &inp->inp_faddr.s_addr, rip, sizeof(rip));
}
else if (inp->inp_vflag & INP_IPV6) {
family = AF_INET6;
inet_ntop(AF_INET6, &inp->in6p_laddr.s6_addr, lip, sizeof(lip));
inet_ntop(AF_INET6, &inp->in6p_faddr.s6_addr, rip, sizeof(rip));
}
// construct python tuple/list
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", rip, rport);
else
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
py_tuple = Py_BuildValue(
"iiiNNi" _Py_PARSE_PID,
xf->xf_fd, // fd
family, // family
type, // type
py_laddr, // laddr
py_raddr, // raddr
status, // status
xf->xf_pid // pid
);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
free(buf);
return 1;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
free(buf);
return 0;
}
int psutil_gather_unix(int proto, PyObject *py_retlist) {
struct xunpgen *xug, *exug;
struct xunpcb *xup;
const char *varname = NULL;
const char *protoname = NULL;
size_t len;
size_t bufsize;
void *buf;
int retry;
struct sockaddr_un *sun;
char path[PATH_MAX];
PyObject *py_tuple = NULL;
PyObject *py_lpath = NULL;
switch (proto) {
case SOCK_STREAM:
varname = "net.local.stream.pcblist";
protoname = "stream";
break;
case SOCK_DGRAM:
varname = "net.local.dgram.pcblist";
protoname = "dgram";
break;
}
buf = NULL;
bufsize = 8192;
retry = 5;
do {
for (;;) {
buf = realloc(buf, bufsize);
if (buf == NULL) {
PyErr_NoMemory();
goto error;
}
len = bufsize;
if (sysctlbyname(varname, buf, &len, NULL, 0) == 0)
break;
if (errno != ENOMEM) {
PyErr_SetFromErrno(0);
goto error;
}
bufsize *= 2;
}
xug = (struct xunpgen *)buf;
exug = (struct xunpgen *)(void *)
((char *)buf + len - sizeof *exug);
if (xug->xug_len != sizeof *xug || exug->xug_len != sizeof *exug) {
PyErr_Format(PyExc_RuntimeError, "struct xinpgen size mismatch");
goto error;
}
} while (xug->xug_gen != exug->xug_gen && retry--);
for (;;) {
struct xfile *xf;
xug = (struct xunpgen *)(void *)((char *)xug + xug->xug_len);
if (xug >= exug)
break;
xup = (struct xunpcb *)xug;
if (xup->xu_len != sizeof *xup)
goto error;
xf = psutil_get_file_from_sock(xup->xu_socket.xso_so);
if (xf == NULL)
continue;
sun = (struct sockaddr_un *)&xup->xu_addr;
snprintf(path, sizeof(path), "%.*s",
(int)(sun->sun_len - (sizeof(*sun) - sizeof(sun->sun_path))),
sun->sun_path);
py_lpath = PyUnicode_DecodeFSDefault(path);
if (! py_lpath)
goto error;
py_tuple = Py_BuildValue("(iiiOsii)",
xf->xf_fd, // fd
AF_UNIX, // family
proto, // type
py_lpath, // lpath
"", // rath
PSUTIL_CONN_NONE, // status
xf->xf_pid); // pid
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_lpath);
Py_DECREF(py_tuple);
}
free(buf);
return 1;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_lpath);
free(buf);
return 0;
}
PyObject*
psutil_net_connections(PyObject* self, PyObject* args) {
// Return system-wide open connections.
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (psutil_populate_xfiles() != 1)
goto error;
if (psutil_gather_inet(IPPROTO_TCP, py_retlist) == 0)
goto error;
if (psutil_gather_inet(IPPROTO_UDP, py_retlist) == 0)
goto error;
if (psutil_gather_unix(SOCK_STREAM, py_retlist) == 0)
goto error;
if (psutil_gather_unix(SOCK_DGRAM, py_retlist) == 0)
goto error;
free(psutil_xfiles);
return py_retlist;
error:
Py_DECREF(py_retlist);
free(psutil_xfiles);
return NULL;
}
| 10,147 | 26.576087 | 78 | c |
psutil | psutil-master/psutil/arch/freebsd/sys_socks.h | /*
* Copyright (c) 2009, Giampaolo Rodola'.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject* psutil_net_connections(PyObject* self, PyObject* args);
| 265 | 23.181818 | 73 | h |
psutil | psutil-master/psutil/arch/netbsd/cpu.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sched.h>
#include <sys/sysctl.h>
#include <uvm/uvm_extern.h>
/*
CPU related functions. Original code was refactored and moved from
psutil/arch/netbsd/specific.c in 2023 (and was moved in there previously
already) from cset 84219ad. For reference, here's the git history with
original(ish) implementations:
- per CPU times: 312442ad2a5b5d0c608476c5ab3e267735c3bc59 (Jan 2016)
- CPU stats: a991494e4502e1235ebc62b5ba450287d0dedec0 (Jan 2016)
*/
PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
size_t size;
struct uvmexp_sysctl uv;
int uvmexp_mib[] = {CTL_VM, VM_UVMEXP2};
size = sizeof(uv);
if (sysctl(uvmexp_mib, 2, &uv, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue(
"IIIIIII",
uv.swtch, // ctx switches
uv.intrs, // interrupts - XXX always 0, will be determined via /proc
uv.softs, // soft interrupts
uv.syscalls, // syscalls - XXX always 0
uv.traps, // traps
uv.faults, // faults
uv.forks // forks
);
}
PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
int mib[3];
int ncpu;
size_t len;
size_t size;
int i;
PyObject *py_cputime = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
// retrieve the number of cpus
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
uint64_t cpu_time[CPUSTATES];
for (i = 0; i < ncpu; i++) {
// per-cpu info
mib[0] = CTL_KERN;
mib[1] = KERN_CP_TIME;
mib[2] = i;
size = sizeof(cpu_time);
if (sysctl(mib, 3, &cpu_time, &size, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
py_cputime = Py_BuildValue(
"(ddddd)",
(double)cpu_time[CP_USER] / CLOCKS_PER_SEC,
(double)cpu_time[CP_NICE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_SYS] / CLOCKS_PER_SEC,
(double)cpu_time[CP_IDLE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_INTR] / CLOCKS_PER_SEC
);
if (!py_cputime)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_DECREF(py_cputime);
}
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
return NULL;
}
| 2,775 | 25.692308 | 77 | c |
psutil | psutil-master/psutil/arch/netbsd/cpu.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_cpu_stats(PyObject *self, PyObject *args);
PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
| 338 | 27.25 | 73 | h |
psutil | psutil-master/psutil/arch/netbsd/disk.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
Disk related functions. Original code was refactored and moved from
psutil/arch/netbsd/specific.c in 2023 (and was moved in there previously
already) from cset 84219ad. For reference, here's the git history with
original(ish) implementations:
- disk IO counters: 312442ad2a5b5d0c608476c5ab3e267735c3bc59 (Jan 2016)
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <sys/disk.h>
PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
int i, dk_ndrive, mib[3];
size_t len;
struct io_sysctl *stats = NULL;
PyObject *py_disk_info = NULL;
PyObject *py_retdict = PyDict_New();
if (py_retdict == NULL)
return NULL;
mib[0] = CTL_HW;
mib[1] = HW_IOSTATS;
mib[2] = sizeof(struct io_sysctl);
len = 0;
if (sysctl(mib, 3, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
dk_ndrive = (int)(len / sizeof(struct io_sysctl));
stats = malloc(len);
if (stats == NULL) {
PyErr_NoMemory();
goto error;
}
if (sysctl(mib, 3, stats, &len, NULL, 0) < 0 ) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < dk_ndrive; i++) {
py_disk_info = Py_BuildValue(
"(KKKK)",
stats[i].rxfer,
stats[i].wxfer,
stats[i].rbytes,
stats[i].wbytes
);
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, stats[i].name, py_disk_info))
goto error;
Py_DECREF(py_disk_info);
}
free(stats);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (stats != NULL)
free(stats);
return NULL;
}
| 1,939 | 24.526316 | 74 | c |
psutil | psutil-master/psutil/arch/netbsd/disk.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_disk_io_counters(PyObject *self, PyObject *args);
| 281 | 24.636364 | 73 | h |
psutil | psutil-master/psutil/arch/netbsd/mem.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
Memory related functions. Original code was refactored and moved from
psutil/arch/netbsd/specific.c in 2023 (and was moved in there previously
already) from cset 84219ad. For reference, here's the git history with
original(ish) implementations:
- virtual memory: 0749a69c01b374ca3e2180aaafc3c95e3b2d91b9 (Oct 2016)
- swap memory: 312442ad2a5b5d0c608476c5ab3e267735c3bc59 (Jan 2016)
*/
#include <Python.h>
#include <sys/swap.h>
#include <sys/sysctl.h>
#include <uvm/uvm_extern.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
// Virtual memory stats, taken from:
// https://github.com/satterly/zabbix-stats/blob/master/src/libs/zbxsysinfo/
// netbsd/memory.c
PyObject *
psutil_virtual_mem(PyObject *self, PyObject *args) {
size_t size;
struct uvmexp_sysctl uv;
int mib[] = {CTL_VM, VM_UVMEXP2};
long long cached;
size = sizeof(uv);
if (sysctl(mib, 2, &uv, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
// Note: zabbix does not include anonpages, but that doesn't match the
// "Cached" value in /proc/meminfo.
// https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L182
cached = (uv.filepages + uv.execpages + uv.anonpages) << uv.pageshift;
return Py_BuildValue(
"LLLLLL",
(long long) uv.npages << uv.pageshift, // total
(long long) uv.free << uv.pageshift, // free
(long long) uv.active << uv.pageshift, // active
(long long) uv.inactive << uv.pageshift, // inactive
(long long) uv.wired << uv.pageshift, // wired
cached // cached
);
}
PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
uint64_t swap_total, swap_free;
struct swapent *swdev;
int nswap, i;
long pagesize = psutil_getpagesize();
nswap = swapctl(SWAP_NSWAP, 0, 0);
if (nswap == 0) {
// This means there's no swap partition.
return Py_BuildValue("(iiiii)", 0, 0, 0, 0, 0);
}
swdev = calloc(nswap, sizeof(*swdev));
if (swdev == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (swapctl(SWAP_STATS, swdev, nswap) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
// Total things up.
swap_total = swap_free = 0;
for (i = 0; i < nswap; i++) {
if (swdev[i].se_flags & SWF_ENABLE) {
swap_total += (uint64_t)swdev[i].se_nblks * DEV_BSIZE;
swap_free += (uint64_t)(swdev[i].se_nblks - swdev[i].se_inuse) * DEV_BSIZE;
}
}
free(swdev);
// Get swap in/out
unsigned int total;
size_t size = sizeof(total);
struct uvmexp_sysctl uv;
int mib[] = {CTL_VM, VM_UVMEXP2};
size = sizeof(uv);
if (sysctl(mib, 2, &uv, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
return Py_BuildValue("(LLLll)",
swap_total,
(swap_total - swap_free),
swap_free,
(long) uv.pgswapin * pagesize, // swap in
(long) uv.pgswapout * pagesize); // swap out
error:
free(swdev);
return NULL;
}
| 3,428 | 29.078947 | 93 | c |
psutil | psutil-master/psutil/arch/netbsd/mem.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_virtual_mem(PyObject *self, PyObject *args);
PyObject *psutil_swap_mem(PyObject *self, PyObject *args);
| 335 | 27 | 73 | h |
psutil | psutil-master/psutil/arch/netbsd/proc.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Platform-specific module methods for NetBSD.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <kvm.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#include "proc.h"
#define PSUTIL_KPT2DOUBLE(t) (t ## _sec + t ## _usec / 1000000.0)
#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
// ============================================================================
// Utility functions
// ============================================================================
int
psutil_kinfo_proc(pid_t pid, kinfo_proc *proc) {
// Fills a kinfo_proc struct based on process pid.
int ret;
int mib[6];
size_t size = sizeof(kinfo_proc);
mib[0] = CTL_KERN;
mib[1] = KERN_PROC2;
mib[2] = KERN_PROC_PID;
mib[3] = pid;
mib[4] = size;
mib[5] = 1;
ret = sysctl((int*)mib, 6, proc, &size, NULL, 0);
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
// sysctl stores 0 in the size if we can't find the process information.
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
return -1;
}
return 0;
}
struct kinfo_file *
kinfo_getfile(pid_t pid, int* cnt) {
// Mimic's FreeBSD kinfo_file call, taking a pid and a ptr to an
// int as arg and returns an array with cnt struct kinfo_file.
int mib[6];
size_t len;
struct kinfo_file* kf;
mib[0] = CTL_KERN;
mib[1] = KERN_FILE2;
mib[2] = KERN_FILE_BYPID;
mib[3] = (int) pid;
mib[4] = sizeof(struct kinfo_file);
mib[5] = 0;
// get the size of what would be returned
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if ((kf = malloc(len)) == NULL) {
PyErr_NoMemory();
return NULL;
}
mib[5] = (int)(len / sizeof(struct kinfo_file));
if (sysctl(mib, 6, kf, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
*cnt = (int)(len / sizeof(struct kinfo_file));
return kf;
}
PyObject *
psutil_proc_cwd(PyObject *self, PyObject *args) {
long pid;
char path[MAXPATHLEN];
size_t pathlen = sizeof path;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
#ifdef KERN_PROC_CWD
int name[] = { CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_CWD};
if (sysctl(name, 4, path, &pathlen, NULL, 0) != 0) {
if (errno == ENOENT)
NoSuchProcess("sysctl -> ENOENT");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
#else
char *buf;
if (asprintf(&buf, "/proc/%d/cwd", (int)pid) < 0) {
PyErr_NoMemory();
return NULL;
}
ssize_t len = readlink(buf, path, sizeof(path) - 1);
free(buf);
if (len == -1) {
if (errno == ENOENT) {
psutil_debug("sysctl(KERN_PROC_CWD) -> ENOENT converted to ''");
return Py_BuildValue("s", "");
}
else {
PyErr_SetFromErrno(PyExc_OSError);
}
return NULL;
}
path[len] = '\0';
#endif
return PyUnicode_DecodeFSDefault(path);
}
// XXX: This is no longer used as per
// https://github.com/giampaolo/psutil/pull/557#issuecomment-171912820
// Current implementation uses /proc instead.
// Left here just in case.
/*
PyObject *
psutil_proc_exe(PyObject *self, PyObject *args) {
#if __NetBSD_Version__ >= 799000000
pid_t pid;
char pathname[MAXPATHLEN];
int error;
int mib[4];
int ret;
size_t size;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
if (pid == 0) {
// else returns ENOENT
return Py_BuildValue("s", "");
}
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = pid;
mib[3] = KERN_PROC_PATHNAME;
size = sizeof(pathname);
error = sysctl(mib, 4, NULL, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
error = sysctl(mib, 4, pathname, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (size == 0 || strlen(pathname) == 0) {
ret = psutil_pid_exists(pid);
if (ret == -1)
return NULL;
else if (ret == 0)
return NoSuchProcess("psutil_pid_exists -> 0");
else
strcpy(pathname, "");
}
return PyUnicode_DecodeFSDefault(pathname);
#else
return Py_BuildValue("s", "");
#endif
}
*/
PyObject *
psutil_proc_num_threads(PyObject *self, PyObject *args) {
// Return number of threads used by process as a Python integer.
long pid;
kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
return Py_BuildValue("l", (long)kp.p_nlwps);
}
PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
pid_t pid;
int mib[5];
int i, nlwps;
ssize_t st;
size_t size;
struct kinfo_lwp *kl = NULL;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "l", &pid))
goto error;
mib[0] = CTL_KERN;
mib[1] = KERN_LWP;
mib[2] = pid;
mib[3] = sizeof(struct kinfo_lwp);
mib[4] = 0;
st = sysctl(mib, 5, NULL, &size, NULL, 0);
if (st == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
mib[4] = size / sizeof(size_t);
kl = malloc(size);
if (kl == NULL) {
PyErr_NoMemory();
goto error;
}
st = sysctl(mib, 5, kl, &size, NULL, 0);
if (st == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
nlwps = (int)(size / sizeof(struct kinfo_lwp));
for (i = 0; i < nlwps; i++) {
if ((&kl[i])->l_stat == LSIDL || (&kl[i])->l_stat == LSZOMB)
continue;
// XXX: we return 2 "user" times because the struct does not provide
// any "system" time.
py_tuple = Py_BuildValue("idd",
(&kl[i])->l_lid,
PSUTIL_KPT2DOUBLE((&kl[i])->l_rtime),
PSUTIL_KPT2DOUBLE((&kl[i])->l_rtime));
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
free(kl);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (kl != NULL)
free(kl);
return NULL;
}
int
psutil_get_proc_list(kinfo_proc **procList, size_t *procCount) {
// Returns a list of all BSD processes on the system. This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount. You are responsible for freeing
// this list (use "free" from System framework).
// On success, the function returns 0.
// On error, the function returns a BSD errno value.
kinfo_proc *result;
// Declaring name as const requires us to cast it when passing it to
// sysctl because the prototype doesn't include the const modifier.
char errbuf[_POSIX2_LINE_MAX];
int cnt;
kvm_t *kd;
assert( procList != NULL);
assert(*procList == NULL);
assert(procCount != NULL);
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
if (kd == NULL) {
PyErr_Format(
PyExc_RuntimeError, "kvm_openfiles() syscall failed: %s", errbuf);
return 1;
}
result = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(kinfo_proc), &cnt);
if (result == NULL) {
PyErr_Format(PyExc_RuntimeError, "kvm_getproc2() syscall failed");
kvm_close(kd);
return 1;
}
*procCount = (size_t)cnt;
size_t mlen = cnt * sizeof(kinfo_proc);
if ((*procList = malloc(mlen)) == NULL) {
PyErr_NoMemory();
kvm_close(kd);
return 1;
}
memcpy(*procList, result, mlen);
assert(*procList != NULL);
kvm_close(kd);
return 0;
}
PyObject *
psutil_proc_cmdline(PyObject *self, PyObject *args) {
pid_t pid;
int mib[4];
int st;
size_t len = 0;
size_t pos = 0;
char *procargs = NULL;
PyObject *py_retlist = PyList_New(0);
PyObject *py_arg = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = pid;
mib[3] = KERN_PROC_ARGV;
st = sysctl(mib, __arraycount(mib), NULL, &len, NULL, 0);
if (st == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ARGV) get size");
goto error;
}
procargs = (char *)malloc(len);
if (procargs == NULL) {
PyErr_NoMemory();
goto error;
}
st = sysctl(mib, __arraycount(mib), procargs, &len, NULL, 0);
if (st == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ARGV)");
goto error;
}
if (len > 0) {
while (pos < len) {
py_arg = PyUnicode_DecodeFSDefault(&procargs[pos]);
if (!py_arg)
goto error;
if (PyList_Append(py_retlist, py_arg))
goto error;
Py_DECREF(py_arg);
pos = pos + strlen(&procargs[pos]) + 1;
}
}
free(procargs);
return py_retlist;
error:
Py_XDECREF(py_arg);
Py_DECREF(py_retlist);
if (procargs != NULL)
free(procargs);
return NULL;
}
PyObject *
psutil_proc_num_fds(PyObject *self, PyObject *args) {
long pid;
int cnt;
struct kinfo_file *freep;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
return NULL;
}
free(freep);
return Py_BuildValue("i", cnt);
}
| 10,328 | 23.889157 | 79 | c |
psutil | psutil-master/psutil/arch/netbsd/proc.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
typedef struct kinfo_proc2 kinfo_proc;
int psutil_kinfo_proc(pid_t pid, kinfo_proc *proc);
struct kinfo_file * kinfo_getfile(pid_t pid, int* cnt);
int psutil_get_proc_list(kinfo_proc **procList, size_t *procCount);
char *psutil_get_cmd_args(pid_t pid, size_t *argsize);
PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args);
PyObject *psutil_proc_connections(PyObject *self, PyObject *args);
PyObject *psutil_proc_cwd(PyObject *self, PyObject *args);
PyObject *psutil_proc_num_fds(PyObject *self, PyObject *args);
PyObject *psutil_proc_threads(PyObject *self, PyObject *args);
PyObject* psutil_proc_exe(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_threads(PyObject* self, PyObject* args);
| 927 | 37.666667 | 73 | h |
psutil | psutil-master/psutil/arch/netbsd/socks.c | /*
* Copyright (c) 2009, Giampaolo Rodola'.
* Copyright (c) 2015, Ryo ONODERA.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/cdefs.h>
#include <arpa/inet.h>
#include <sys/queue.h>
#include <sys/un.h>
#include <sys/file.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
// address family filter
enum af_filter {
INET,
INET4,
INET6,
TCP,
TCP4,
TCP6,
UDP,
UDP4,
UDP6,
UNIX,
ALL,
};
// kinfo_file results
struct kif {
SLIST_ENTRY(kif) kifs;
struct kinfo_file *kif;
};
// kinfo_file results list
SLIST_HEAD(kifhead, kif) kihead = SLIST_HEAD_INITIALIZER(kihead);
// kinfo_pcb results
struct kpcb {
SLIST_ENTRY(kpcb) kpcbs;
struct kinfo_pcb *kpcb;
};
// kinfo_pcb results list
SLIST_HEAD(kpcbhead, kpcb) kpcbhead = SLIST_HEAD_INITIALIZER(kpcbhead);
static void psutil_kiflist_init(void);
static void psutil_kiflist_clear(void);
static void psutil_kpcblist_init(void);
static void psutil_kpcblist_clear(void);
static int psutil_get_files(void);
static int psutil_get_sockets(const char *name);
static int psutil_get_info(int aff);
// Initialize kinfo_file results list.
static void
psutil_kiflist_init(void) {
SLIST_INIT(&kihead);
return;
}
// Clear kinfo_file results list.
static void
psutil_kiflist_clear(void) {
while (!SLIST_EMPTY(&kihead)) {
SLIST_REMOVE_HEAD(&kihead, kifs);
}
return;
}
// Initialize kinof_pcb result list.
static void
psutil_kpcblist_init(void) {
SLIST_INIT(&kpcbhead);
return;
}
// Clear kinof_pcb result list.
static void
psutil_kpcblist_clear(void) {
while (!SLIST_EMPTY(&kpcbhead)) {
SLIST_REMOVE_HEAD(&kpcbhead, kpcbs);
}
return;
}
// Get all open files including socket.
static int
psutil_get_files(void) {
size_t len;
size_t j;
int mib[6];
char *buf;
off_t offset;
mib[0] = CTL_KERN;
mib[1] = KERN_FILE2;
mib[2] = KERN_FILE_BYFILE;
mib[3] = 0;
mib[4] = sizeof(struct kinfo_file);
mib[5] = 0;
if (sysctl(mib, 6, NULL, &len, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
offset = len % sizeof(off_t);
mib[5] = len / sizeof(struct kinfo_file);
if ((buf = malloc(len + offset)) == NULL) {
PyErr_NoMemory();
return -1;
}
if (sysctl(mib, 6, buf + offset, &len, NULL, 0) == -1) {
free(buf);
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
len /= sizeof(struct kinfo_file);
struct kinfo_file *ki = (struct kinfo_file *)(buf + offset);
for (j = 0; j < len; j++) {
struct kif *kif = malloc(sizeof(struct kif));
kif->kif = &ki[j];
SLIST_INSERT_HEAD(&kihead, kif, kifs);
}
/*
// debug
struct kif *k;
SLIST_FOREACH(k, &kihead, kifs) {
printf("%d\n", k->kif->ki_pid); // NOQA
}
*/
return 0;
}
// Get open sockets.
static int
psutil_get_sockets(const char *name) {
size_t namelen;
int mib[8];
struct kinfo_pcb *pcb;
size_t len;
size_t j;
memset(mib, 0, sizeof(mib));
if (sysctlnametomib(name, mib, &namelen) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (sysctl(mib, __arraycount(mib), NULL, &len, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if ((pcb = malloc(len)) == NULL) {
PyErr_NoMemory();
return -1;
}
memset(pcb, 0, len);
mib[6] = sizeof(*pcb);
mib[7] = len / sizeof(*pcb);
if (sysctl(mib, __arraycount(mib), pcb, &len, NULL, 0) == -1) {
free(pcb);
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
len /= sizeof(struct kinfo_pcb);
struct kinfo_pcb *kp = (struct kinfo_pcb *)pcb;
for (j = 0; j < len; j++) {
struct kpcb *kpcb = malloc(sizeof(struct kpcb));
kpcb->kpcb = &kp[j];
SLIST_INSERT_HEAD(&kpcbhead, kpcb, kpcbs);
}
return 0;
}
// Collect open file and connections.
static int
psutil_get_info(int aff) {
switch (aff) {
case INET:
if (psutil_get_sockets("net.inet.tcp.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet.udp.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet6.tcp6.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet6.udp6.pcblist") != 0)
return -1;
break;
case INET4:
if (psutil_get_sockets("net.inet.tcp.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet.udp.pcblist") != 0)
return -1;
break;
case INET6:
if (psutil_get_sockets("net.inet6.tcp6.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet6.udp6.pcblist") != 0)
return -1;
break;
case TCP:
if (psutil_get_sockets("net.inet.tcp.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet6.tcp6.pcblist") != 0)
return -1;
break;
case TCP4:
if (psutil_get_sockets("net.inet.tcp.pcblist") != 0)
return -1;
break;
case TCP6:
if (psutil_get_sockets("net.inet6.tcp6.pcblist") != 0)
return -1;
break;
case UDP:
if (psutil_get_sockets("net.inet.udp.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet6.udp6.pcblist") != 0)
return -1;
break;
case UDP4:
if (psutil_get_sockets("net.inet.udp.pcblist") != 0)
return -1;
break;
case UDP6:
if (psutil_get_sockets("net.inet6.udp6.pcblist") != 0)
return -1;
break;
case UNIX:
if (psutil_get_sockets("net.local.stream.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.local.seqpacket.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.local.dgram.pcblist") != 0)
return -1;
break;
case ALL:
if (psutil_get_sockets("net.inet.tcp.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet.udp.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet6.tcp6.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.inet6.udp6.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.local.stream.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.local.seqpacket.pcblist") != 0)
return -1;
if (psutil_get_sockets("net.local.dgram.pcblist") != 0)
return -1;
break;
}
return 0;
}
/*
* Return system-wide connections (unless a pid != -1 is passed).
*/
PyObject *
psutil_net_connections(PyObject *self, PyObject *args) {
char laddr[PATH_MAX];
char raddr[PATH_MAX];
int32_t lport;
int32_t rport;
int32_t status;
pid_t pid;
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
psutil_kiflist_init();
psutil_kpcblist_init();
if (psutil_get_files() != 0)
goto error;
if (psutil_get_info(ALL) != 0)
goto error;
struct kif *k;
SLIST_FOREACH(k, &kihead, kifs) {
struct kpcb *kp;
if ((pid != -1) && (k->kif->ki_pid != (unsigned int)pid))
continue;
SLIST_FOREACH(kp, &kpcbhead, kpcbs) {
if (k->kif->ki_fdata != kp->kpcb->ki_sockaddr)
continue;
// IPv4 or IPv6
if ((kp->kpcb->ki_family == AF_INET) ||
(kp->kpcb->ki_family == AF_INET6)) {
if (kp->kpcb->ki_family == AF_INET) {
// IPv4
struct sockaddr_in *sin_src =
(struct sockaddr_in *)&kp->kpcb->ki_src;
struct sockaddr_in *sin_dst =
(struct sockaddr_in *)&kp->kpcb->ki_dst;
// source addr and port
inet_ntop(AF_INET, &sin_src->sin_addr, laddr,
sizeof(laddr));
lport = ntohs(sin_src->sin_port);
// remote addr and port
inet_ntop(AF_INET, &sin_dst->sin_addr, raddr,
sizeof(raddr));
rport = ntohs(sin_dst->sin_port);
}
else {
// IPv6
struct sockaddr_in6 *sin6_src =
(struct sockaddr_in6 *)&kp->kpcb->ki_src;
struct sockaddr_in6 *sin6_dst =
(struct sockaddr_in6 *)&kp->kpcb->ki_dst;
// local addr and port
inet_ntop(AF_INET6, &sin6_src->sin6_addr, laddr,
sizeof(laddr));
lport = ntohs(sin6_src->sin6_port);
// remote addr and port
inet_ntop(AF_INET6, &sin6_dst->sin6_addr, raddr,
sizeof(raddr));
rport = ntohs(sin6_dst->sin6_port);
}
// status
if (kp->kpcb->ki_type == SOCK_STREAM)
status = kp->kpcb->ki_tstate;
else
status = PSUTIL_CONN_NONE;
// build addr tuple
py_laddr = Py_BuildValue("(si)", laddr, lport);
if (! py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", raddr, rport);
else
py_raddr = Py_BuildValue("()");
if (! py_raddr)
goto error;
}
else if (kp->kpcb->ki_family == AF_UNIX) {
// UNIX sockets
struct sockaddr_un *sun_src =
(struct sockaddr_un *)&kp->kpcb->ki_src;
struct sockaddr_un *sun_dst =
(struct sockaddr_un *)&kp->kpcb->ki_dst;
strcpy(laddr, sun_src->sun_path);
strcpy(raddr, sun_dst->sun_path);
status = PSUTIL_CONN_NONE;
py_laddr = PyUnicode_DecodeFSDefault(laddr);
if (! py_laddr)
goto error;
py_raddr = PyUnicode_DecodeFSDefault(raddr);
if (! py_raddr)
goto error;
}
else {
continue;
}
// append tuple to list
py_tuple = Py_BuildValue(
"(iiiOOii)",
k->kif->ki_fd,
kp->kpcb->ki_family,
kp->kpcb->ki_type,
py_laddr,
py_raddr,
status,
k->kif->ki_pid);
if (! py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_laddr);
Py_DECREF(py_raddr);
Py_DECREF(py_tuple);
}
}
psutil_kiflist_clear();
psutil_kpcblist_clear();
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
return 0;
}
| 12,007 | 26.478261 | 73 | c |
psutil | psutil-master/psutil/arch/netbsd/socks.h | /*
* Copyright (c) 2009, Giampaolo Rodola'.
* Copyright (c) 2015, Ryo ONODERA.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
PyObject *psutil_proc_connections(PyObject *, PyObject *);
PyObject *psutil_net_connections(PyObject *, PyObject *);
| 331 | 29.181818 | 73 | h |
psutil | psutil-master/psutil/arch/openbsd/cpu.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <sys/sched.h> // for CPUSTATES & CP_*
PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
int mib[3];
int ncpu;
size_t len;
size_t size;
int i;
PyObject *py_retlist = PyList_New(0);
PyObject *py_cputime = NULL;
if (py_retlist == NULL)
return NULL;
// retrieve the number of cpus
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
uint64_t cpu_time[CPUSTATES];
for (i = 0; i < ncpu; i++) {
mib[0] = CTL_KERN;
mib[1] = KERN_CPTIME2;
mib[2] = i;
size = sizeof(cpu_time);
if (sysctl(mib, 3, &cpu_time, &size, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
py_cputime = Py_BuildValue(
"(ddddd)",
(double)cpu_time[CP_USER] / CLOCKS_PER_SEC,
(double)cpu_time[CP_NICE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_SYS] / CLOCKS_PER_SEC,
(double)cpu_time[CP_IDLE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_INTR] / CLOCKS_PER_SEC);
if (!py_cputime)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_DECREF(py_cputime);
}
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
return NULL;
}
PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
size_t size;
struct uvmexp uv;
int uvmexp_mib[] = {CTL_VM, VM_UVMEXP};
size = sizeof(uv);
if (sysctl(uvmexp_mib, 2, &uv, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue(
"IIIIIII",
uv.swtch, // ctx switches
uv.intrs, // interrupts - XXX always 0, will be determined via /proc
uv.softs, // soft interrupts
uv.syscalls, // syscalls - XXX always 0
uv.traps, // traps
uv.faults, // faults
uv.forks // forks
);
}
PyObject *
psutil_cpu_freq(PyObject *self, PyObject *args) {
int freq;
size_t size;
int mib[2] = {CTL_HW, HW_CPUSPEED};
// On VirtualBox I get "sysctl hw.cpuspeed=2593" (never changing),
// which appears to be expressed in Mhz.
size = sizeof(freq);
if (sysctl(mib, 2, &freq, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue("i", freq);
}
| 2,787 | 24.345455 | 77 | c |
psutil | psutil-master/psutil/arch/openbsd/cpu.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_cpu_freq(PyObject* self, PyObject* args);
PyObject *psutil_cpu_stats(PyObject* self, PyObject* args);
PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
| 397 | 29.615385 | 73 | h |
psutil | psutil-master/psutil/arch/openbsd/disk.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <sys/disk.h>
PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
int i, dk_ndrive, mib[3];
size_t len;
struct diskstats *stats = NULL;
PyObject *py_retdict = PyDict_New();
PyObject *py_disk_info = NULL;
if (py_retdict == NULL)
return NULL;
mib[0] = CTL_HW;
mib[1] = HW_DISKSTATS;
len = 0;
if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
dk_ndrive = (int)(len / sizeof(struct diskstats));
stats = malloc(len);
if (stats == NULL) {
PyErr_NoMemory();
goto error;
}
if (sysctl(mib, 2, stats, &len, NULL, 0) < 0 ) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < dk_ndrive; i++) {
py_disk_info = Py_BuildValue(
"(KKKK)",
stats[i].ds_rxfer, // num reads
stats[i].ds_wxfer, // num writes
stats[i].ds_rbytes, // read bytes
stats[i].ds_wbytes // write bytes
);
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, stats[i].ds_name, py_disk_info))
goto error;
Py_DECREF(py_disk_info);
}
free(stats);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (stats != NULL)
free(stats);
return NULL;
}
| 1,656 | 23.367647 | 77 | c |
psutil | psutil-master/psutil/arch/openbsd/disk.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_disk_io_counters(PyObject* self, PyObject* args);
| 281 | 24.636364 | 73 | h |
psutil | psutil-master/psutil/arch/openbsd/mem.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <sys/mount.h>
#include <sys/swap.h>
#include <sys/param.h>
#include "../../_psutil_posix.h"
PyObject *
psutil_virtual_mem(PyObject *self, PyObject *args) {
int64_t total_physmem;
int uvmexp_mib[] = {CTL_VM, VM_UVMEXP};
int bcstats_mib[] = {CTL_VFS, VFS_GENERIC, VFS_BCACHESTAT};
int physmem_mib[] = {CTL_HW, HW_PHYSMEM64};
int vmmeter_mib[] = {CTL_VM, VM_METER};
size_t size;
struct uvmexp uvmexp;
struct bcachestats bcstats;
struct vmtotal vmdata;
long pagesize = psutil_getpagesize();
size = sizeof(total_physmem);
if (sysctl(physmem_mib, 2, &total_physmem, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
size = sizeof(uvmexp);
if (sysctl(uvmexp_mib, 2, &uvmexp, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
size = sizeof(bcstats);
if (sysctl(bcstats_mib, 3, &bcstats, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
size = sizeof(vmdata);
if (sysctl(vmmeter_mib, 2, &vmdata, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue("KKKKKKKK",
// Note: many programs calculate total memory as
// "uvmexp.npages * pagesize" but this is incorrect and does not
// match "sysctl | grep hw.physmem".
(unsigned long long) total_physmem,
(unsigned long long) uvmexp.free * pagesize,
(unsigned long long) uvmexp.active * pagesize,
(unsigned long long) uvmexp.inactive * pagesize,
(unsigned long long) uvmexp.wired * pagesize,
// this is how "top" determines it
(unsigned long long) bcstats.numbufpages * pagesize, // cached
(unsigned long long) 0, // buffers
(unsigned long long) vmdata.t_vmshr + vmdata.t_rmshr // shared
);
}
PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
uint64_t swap_total, swap_free;
struct swapent *swdev;
int nswap, i;
if ((nswap = swapctl(SWAP_NSWAP, 0, 0)) == 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if ((swdev = calloc(nswap, sizeof(*swdev))) == NULL) {
PyErr_NoMemory();
return NULL;
}
if (swapctl(SWAP_STATS, swdev, nswap) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
// Total things up.
swap_total = swap_free = 0;
for (i = 0; i < nswap; i++) {
if (swdev[i].se_flags & SWF_ENABLE) {
swap_free += (swdev[i].se_nblks - swdev[i].se_inuse);
swap_total += swdev[i].se_nblks;
}
}
free(swdev);
return Py_BuildValue(
"(LLLII)",
swap_total * DEV_BSIZE,
(swap_total - swap_free) * DEV_BSIZE,
swap_free * DEV_BSIZE,
// swap in / swap out is not supported as the
// swapent struct does not provide any info
// about it.
0,
0
);
error:
free(swdev);
return NULL;
}
| 3,312 | 26.840336 | 73 | c |
psutil | psutil-master/psutil/arch/openbsd/mem.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_virtual_mem(PyObject *self, PyObject *args);
PyObject *psutil_swap_mem(PyObject *self, PyObject *args);
| 335 | 27 | 73 | h |
psutil | psutil-master/psutil/arch/openbsd/proc.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/proc.h>
#include <kvm.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#define PSUTIL_KPT2DOUBLE(t) (t ## _sec + t ## _usec / 1000000.0)
// #define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
// ============================================================================
// Utility functions
// ============================================================================
int
psutil_kinfo_proc(pid_t pid, struct kinfo_proc *proc) {
// Fills a kinfo_proc struct based on process pid.
int ret;
int mib[6];
size_t size = sizeof(struct kinfo_proc);
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = pid;
mib[4] = size;
mib[5] = 1;
ret = sysctl((int*)mib, 6, proc, &size, NULL, 0);
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
// sysctl stores 0 in the size if we can't find the process information.
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
return -1;
}
return 0;
}
struct kinfo_file *
kinfo_getfile(pid_t pid, int* cnt) {
// Mimic's FreeBSD kinfo_file call, taking a pid and a ptr to an
// int as arg and returns an array with cnt struct kinfo_file.
int mib[6];
size_t len;
struct kinfo_file* kf;
mib[0] = CTL_KERN;
mib[1] = KERN_FILE;
mib[2] = KERN_FILE_BYPID;
mib[3] = pid;
mib[4] = sizeof(struct kinfo_file);
mib[5] = 0;
/* get the size of what would be returned */
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if ((kf = malloc(len)) == NULL) {
PyErr_NoMemory();
return NULL;
}
mib[5] = (int)(len / sizeof(struct kinfo_file));
if (sysctl(mib, 6, kf, &len, NULL, 0) < 0) {
free(kf);
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
*cnt = (int)(len / sizeof(struct kinfo_file));
return kf;
}
// ============================================================================
// APIS
// ============================================================================
int
psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount) {
// Returns a list of all BSD processes on the system. This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount. You are responsible for freeing
// this list (use "free" from System framework).
// On success, the function returns 0.
// On error, the function returns a BSD errno value.
struct kinfo_proc *result;
// Declaring name as const requires us to cast it when passing it to
// sysctl because the prototype doesn't include the const modifier.
char errbuf[_POSIX2_LINE_MAX];
int cnt;
kvm_t *kd;
assert(procList != NULL);
assert(*procList == NULL);
assert(procCount != NULL);
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
if (! kd) {
convert_kvm_err("kvm_openfiles", errbuf);
return 1;
}
result = kvm_getprocs(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &cnt);
if (result == NULL) {
PyErr_Format(PyExc_RuntimeError, "kvm_getprocs syscall failed");
kvm_close(kd);
return 1;
}
*procCount = (size_t)cnt;
size_t mlen = cnt * sizeof(struct kinfo_proc);
if ((*procList = malloc(mlen)) == NULL) {
PyErr_NoMemory();
kvm_close(kd);
return 1;
}
memcpy(*procList, result, mlen);
assert(*procList != NULL);
kvm_close(kd);
return 0;
}
// TODO: refactor this (it's clunky)
PyObject *
psutil_proc_cmdline(PyObject *self, PyObject *args) {
pid_t pid;
int mib[4];
static char **argv;
char **p;
size_t argv_size = 128;
PyObject *py_retlist = PyList_New(0);
PyObject *py_arg = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = pid;
mib[3] = KERN_PROC_ARGV;
// Loop and reallocate until we have enough space to fit argv.
for (;; argv_size *= 2) {
if (argv_size >= 8192) {
PyErr_SetString(PyExc_RuntimeError,
"can't allocate enough space for KERN_PROC_ARGV");
goto error;
}
if ((argv = realloc(argv, argv_size)) == NULL)
continue;
if (sysctl(mib, 4, argv, &argv_size, NULL, 0) == 0)
break;
if (errno == ENOMEM)
continue;
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (p = argv; *p != NULL; p++) {
py_arg = PyUnicode_DecodeFSDefault(*p);
if (!py_arg)
goto error;
if (PyList_Append(py_retlist, py_arg))
goto error;
Py_DECREF(py_arg);
}
return py_retlist;
error:
Py_XDECREF(py_arg);
Py_DECREF(py_retlist);
return NULL;
}
PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
// OpenBSD reference:
// https://github.com/janmojzis/pstree/blob/master/proc_kvm.c
// Note: this requires root access, else it will fail trying
// to access /dev/kmem.
pid_t pid;
kvm_t *kd = NULL;
int nentries, i;
char errbuf[4096];
struct kinfo_proc *kp;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
kd = kvm_openfiles(0, 0, 0, O_RDONLY, errbuf);
if (! kd) {
convert_kvm_err("kvm_openfiles()", errbuf);
goto error;
}
kp = kvm_getprocs(
kd, KERN_PROC_PID | KERN_PROC_SHOW_THREADS | KERN_PROC_KTHREAD, pid,
sizeof(*kp), &nentries);
if (! kp) {
if (strstr(errbuf, "Permission denied") != NULL)
AccessDenied("kvm_getprocs");
else
PyErr_Format(PyExc_RuntimeError, "kvm_getprocs() syscall failed");
goto error;
}
for (i = 0; i < nentries; i++) {
if (kp[i].p_tid < 0)
continue;
if (kp[i].p_pid == pid) {
py_tuple = Py_BuildValue(
_Py_PARSE_PID "dd",
kp[i].p_tid,
PSUTIL_KPT2DOUBLE(kp[i].p_uutime),
PSUTIL_KPT2DOUBLE(kp[i].p_ustime));
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
}
kvm_close(kd);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (kd != NULL)
kvm_close(kd);
return NULL;
}
PyObject *
psutil_proc_num_fds(PyObject *self, PyObject *args) {
pid_t pid;
int cnt;
struct kinfo_file *freep;
struct kinfo_proc kipp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kipp) == -1)
return NULL;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL)
return NULL;
free(freep);
return Py_BuildValue("i", cnt);
}
PyObject *
psutil_proc_cwd(PyObject *self, PyObject *args) {
// Reference:
// https://github.com/openbsd/src/blob/
// 588f7f8c69786211f2d16865c552afb91b1c7cba/bin/ps/print.c#L191
pid_t pid;
struct kinfo_proc kp;
char path[MAXPATHLEN];
size_t pathlen = sizeof path;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
int name[] = { CTL_KERN, KERN_PROC_CWD, pid };
if (sysctl(name, 3, path, &pathlen, NULL, 0) != 0) {
if (errno == ENOENT) {
psutil_debug("sysctl(KERN_PROC_CWD) -> ENOENT converted to ''");
return Py_BuildValue("s", "");
}
else {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
}
return PyUnicode_DecodeFSDefault(path);
}
| 8,398 | 25.495268 | 81 | c |
psutil | psutil-master/psutil/arch/openbsd/proc.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
typedef struct kinfo_proc kinfo_proc;
int psutil_kinfo_proc(pid_t pid, struct kinfo_proc *proc);
struct kinfo_file * kinfo_getfile(pid_t pid, int* cnt);
int psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount);
char **_psutil_get_argv(pid_t pid);
PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args);
PyObject *psutil_proc_threads(PyObject *self, PyObject *args);
PyObject *psutil_proc_num_fds(PyObject *self, PyObject *args);
PyObject *psutil_proc_cwd(PyObject *self, PyObject *args);
| 728 | 33.714286 | 74 | h |
psutil | psutil-master/psutil/arch/openbsd/socks.c | /*
* Copyright (c) 2009, Giampaolo Rodola'.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <kvm.h>
#define _KERNEL // silence compiler warning
#include <sys/file.h> // DTYPE_SOCKET
#include <netdb.h> // INET6_ADDRSTRLEN, in6_addr
#undef _KERNEL
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
PyObject *
psutil_net_connections(PyObject *self, PyObject *args) {
pid_t pid;
int i;
int cnt;
int state;
int lport;
int rport;
char lip[INET6_ADDRSTRLEN];
char rip[INET6_ADDRSTRLEN];
int inseq;
char errbuf[_POSIX2_LINE_MAX];
kvm_t *kd = NULL;
struct kinfo_file *kif;
struct kinfo_file *ikf;
struct in6_addr laddr6;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
PyObject *py_lpath = NULL;
PyObject *py_af_filter = NULL;
PyObject *py_type_filter = NULL;
PyObject *py_family = NULL;
PyObject *_type = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID "OO", &pid, &py_af_filter,
&py_type_filter)) {
goto error;
}
if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) {
PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
goto error;
}
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
if (! kd) {
convert_kvm_err("kvm_openfiles", errbuf);
goto error;
}
ikf = kvm_getfiles(kd, KERN_FILE_BYPID, -1, sizeof(*ikf), &cnt);
if (! ikf) {
PyErr_SetFromOSErrnoWithSyscall("kvm_getfiles");
goto error;
}
for (int i = 0; i < cnt; i++) {
const struct kinfo_file *kif = ikf + i;
py_tuple = NULL;
py_laddr = NULL;
py_raddr = NULL;
py_lpath = NULL;
// apply filters
if (kif->f_type != DTYPE_SOCKET)
continue;
if (pid != -1 && kif->p_pid != (uint32_t)pid)
continue;
py_family = PyLong_FromLong((long)kif->so_family);
inseq = PySequence_Contains(py_af_filter, py_family);
Py_DECREF(py_family);
if (inseq == 0)
continue;
_type = PyLong_FromLong((long)kif->so_type);
inseq = PySequence_Contains(py_type_filter, _type);
Py_DECREF(_type);
if (inseq == 0)
continue;
// IPv4 / IPv6 socket
if ((kif->so_family == AF_INET) || (kif->so_family == AF_INET6)) {
// status
if (kif->so_type == SOCK_STREAM)
state = kif->t_state;
else
state = PSUTIL_CONN_NONE;
// local & remote port
lport = ntohs(kif->inp_lport);
rport = ntohs(kif->inp_fport);
// local addr
inet_ntop(kif->so_family, &kif->inp_laddru, lip, sizeof(lip));
py_laddr = Py_BuildValue("(si)", lip, lport);
if (! py_laddr)
goto error;
// remote addr
if (rport != 0) {
inet_ntop(kif->so_family, &kif->inp_faddru, rip, sizeof(rip));
py_raddr = Py_BuildValue("(si)", rip, rport);
}
else {
py_raddr = Py_BuildValue("()");
}
if (! py_raddr)
goto error;
// populate tuple and list
py_tuple = Py_BuildValue(
"(iiiNNil)",
kif->fd_fd,
kif->so_family,
kif->so_type,
py_laddr,
py_raddr,
state,
kif->p_pid
);
if (! py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
// UNIX socket
else if (kif->so_family == AF_UNIX) {
py_lpath = PyUnicode_DecodeFSDefault(kif->unp_path);
if (! py_lpath)
goto error;
py_tuple = Py_BuildValue(
"(iiiOsil)",
kif->fd_fd,
kif->so_family,
kif->so_type,
py_lpath,
"", // raddr
PSUTIL_CONN_NONE,
kif->p_pid
);
if (! py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_lpath);
Py_DECREF(py_tuple);
Py_INCREF(Py_None);
}
}
kvm_close(kd);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
Py_DECREF(py_retlist);
if (kd != NULL)
kvm_close(kd);
return NULL;
}
| 4,993 | 26.59116 | 79 | c |
psutil | psutil-master/psutil/arch/openbsd/socks.h | /*
* Copyright (c) 2009, Giampaolo Rodola'.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
PyObject *psutil_net_connections(PyObject* self, PyObject* args);
| 244 | 26.222222 | 73 | h |
psutil | psutil-master/psutil/arch/osx/cpu.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
System-wide CPU related functions.
Original code was refactored and moved from psutil/_psutil_osx.c in 2020
right before a4c0a0eb0d2a872ab7a45e47fcf37ef1fde5b012.
For reference, here's the git history with original implementations:
- CPU count logical: 3d291d425b856077e65163e43244050fb188def1
- CPU count physical: 4263e354bb4984334bc44adf5dd2f32013d69fba
- CPU times: 32488bdf54aed0f8cef90d639c1667ffaa3c31c7
- CPU stat: fa00dfb961ef63426c7818899340866ced8d2418
- CPU frequency: 6ba1ac4ebfcd8c95fca324b15606ab0ec1412d39
*/
#include <Python.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/mach_port.h>
#include <mach/mach_vm.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <mach/mach.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
PyObject *
psutil_cpu_count_logical(PyObject *self, PyObject *args) {
int num;
size_t size = sizeof(int);
if (sysctlbyname("hw.logicalcpu", &num, &size, NULL, 2))
Py_RETURN_NONE; // mimic os.cpu_count()
else
return Py_BuildValue("i", num);
}
PyObject *
psutil_cpu_count_cores(PyObject *self, PyObject *args) {
int num;
size_t size = sizeof(int);
if (sysctlbyname("hw.physicalcpu", &num, &size, NULL, 0))
Py_RETURN_NONE; // mimic os.cpu_count()
else
return Py_BuildValue("i", num);
}
PyObject *
psutil_cpu_times(PyObject *self, PyObject *args) {
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
kern_return_t error;
host_cpu_load_info_data_t r_load;
mach_port_t host_port = mach_host_self();
error = host_statistics(host_port, HOST_CPU_LOAD_INFO,
(host_info_t)&r_load, &count);
if (error != KERN_SUCCESS) {
return PyErr_Format(
PyExc_RuntimeError,
"host_statistics(HOST_CPU_LOAD_INFO) syscall failed: %s",
mach_error_string(error));
}
mach_port_deallocate(mach_task_self(), host_port);
return Py_BuildValue(
"(dddd)",
(double)r_load.cpu_ticks[CPU_STATE_USER] / CLK_TCK,
(double)r_load.cpu_ticks[CPU_STATE_NICE] / CLK_TCK,
(double)r_load.cpu_ticks[CPU_STATE_SYSTEM] / CLK_TCK,
(double)r_load.cpu_ticks[CPU_STATE_IDLE] / CLK_TCK
);
}
PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
struct vmmeter vmstat;
kern_return_t ret;
mach_msg_type_number_t count = sizeof(vmstat) / sizeof(integer_t);
mach_port_t mport = mach_host_self();
ret = host_statistics(mport, HOST_VM_INFO, (host_info_t)&vmstat, &count);
if (ret != KERN_SUCCESS) {
PyErr_Format(
PyExc_RuntimeError,
"host_statistics(HOST_VM_INFO) failed: %s",
mach_error_string(ret));
return NULL;
}
mach_port_deallocate(mach_task_self(), mport);
return Py_BuildValue(
"IIIII",
vmstat.v_swtch, // ctx switches
vmstat.v_intr, // interrupts
vmstat.v_soft, // software interrupts
vmstat.v_syscall, // syscalls
vmstat.v_trap // traps
);
}
PyObject *
psutil_cpu_freq(PyObject *self, PyObject *args) {
unsigned int curr;
int64_t min = 0;
int64_t max = 0;
int mib[2];
size_t len = sizeof(curr);
size_t size = sizeof(min);
// also available as "hw.cpufrequency" but it's deprecated
mib[0] = CTL_HW;
mib[1] = HW_CPU_FREQ;
if (sysctl(mib, 2, &curr, &len, NULL, 0) < 0)
return PyErr_SetFromOSErrnoWithSyscall("sysctl(HW_CPU_FREQ)");
if (sysctlbyname("hw.cpufrequency_min", &min, &size, NULL, 0))
psutil_debug("sysctl('hw.cpufrequency_min') failed (set to 0)");
if (sysctlbyname("hw.cpufrequency_max", &max, &size, NULL, 0))
psutil_debug("sysctl('hw.cpufrequency_min') failed (set to 0)");
return Py_BuildValue(
"IKK",
curr / 1000 / 1000,
min / 1000 / 1000,
max / 1000 / 1000);
}
PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
natural_t cpu_count;
natural_t i;
processor_info_array_t info_array;
mach_msg_type_number_t info_count;
kern_return_t error;
processor_cpu_load_info_data_t *cpu_load_info = NULL;
int ret;
PyObject *py_retlist = PyList_New(0);
PyObject *py_cputime = NULL;
if (py_retlist == NULL)
return NULL;
mach_port_t host_port = mach_host_self();
error = host_processor_info(host_port, PROCESSOR_CPU_LOAD_INFO,
&cpu_count, &info_array, &info_count);
if (error != KERN_SUCCESS) {
PyErr_Format(
PyExc_RuntimeError,
"host_processor_info(PROCESSOR_CPU_LOAD_INFO) syscall failed: %s",
mach_error_string(error));
goto error;
}
mach_port_deallocate(mach_task_self(), host_port);
cpu_load_info = (processor_cpu_load_info_data_t *) info_array;
for (i = 0; i < cpu_count; i++) {
py_cputime = Py_BuildValue(
"(dddd)",
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_USER] / CLK_TCK,
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_NICE] / CLK_TCK,
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM] / CLK_TCK,
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE] / CLK_TCK
);
if (!py_cputime)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_CLEAR(py_cputime);
}
ret = vm_deallocate(mach_task_self(), (vm_address_t)info_array,
info_count * sizeof(int));
if (ret != KERN_SUCCESS)
PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
if (cpu_load_info != NULL) {
ret = vm_deallocate(mach_task_self(), (vm_address_t)info_array,
info_count * sizeof(int));
if (ret != KERN_SUCCESS)
PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
}
return NULL;
}
| 6,233 | 29.558824 | 78 | c |
psutil | psutil-master/psutil/arch/osx/cpu.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_cpu_count_cores(PyObject *self, PyObject *args);
PyObject *psutil_cpu_count_logical(PyObject *self, PyObject *args);
PyObject *psutil_cpu_freq(PyObject *self, PyObject *args);
PyObject *psutil_cpu_stats(PyObject *self, PyObject *args);
PyObject *psutil_cpu_times(PyObject *self, PyObject *args);
PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
| 584 | 38 | 73 | h |
psutil | psutil-master/psutil/arch/osx/disk.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// Disk related functions. Original code was refactored and moved
// from psutil/_psutil_osx.c in 2023. This is the GIT blame before the move:
// https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_osx.c
#include <Python.h>
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/storage/IOBlockStorageDriver.h>
#include <IOKit/storage/IOMedia.h>
#include <IOKit/IOBSD.h>
#include "../../_psutil_common.h"
/*
* Return a list of tuples including device, mount point and fs type
* for all partitions mounted on the system.
*/
PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
int num;
int i;
int len;
uint64_t flags;
char opts[400];
struct statfs *fs = NULL;
PyObject *py_dev = NULL;
PyObject *py_mountp = NULL;
PyObject *py_tuple = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
// get the number of mount points
Py_BEGIN_ALLOW_THREADS
num = getfsstat(NULL, 0, MNT_NOWAIT);
Py_END_ALLOW_THREADS
if (num == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
len = sizeof(*fs) * num;
fs = malloc(len);
if (fs == NULL) {
PyErr_NoMemory();
goto error;
}
Py_BEGIN_ALLOW_THREADS
num = getfsstat(fs, len, MNT_NOWAIT);
Py_END_ALLOW_THREADS
if (num == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < num; i++) {
opts[0] = 0;
flags = fs[i].f_flags;
// see sys/mount.h
if (flags & MNT_RDONLY)
strlcat(opts, "ro", sizeof(opts));
else
strlcat(opts, "rw", sizeof(opts));
if (flags & MNT_SYNCHRONOUS)
strlcat(opts, ",sync", sizeof(opts));
if (flags & MNT_NOEXEC)
strlcat(opts, ",noexec", sizeof(opts));
if (flags & MNT_NOSUID)
strlcat(opts, ",nosuid", sizeof(opts));
if (flags & MNT_UNION)
strlcat(opts, ",union", sizeof(opts));
if (flags & MNT_ASYNC)
strlcat(opts, ",async", sizeof(opts));
if (flags & MNT_EXPORTED)
strlcat(opts, ",exported", sizeof(opts));
if (flags & MNT_QUARANTINE)
strlcat(opts, ",quarantine", sizeof(opts));
if (flags & MNT_LOCAL)
strlcat(opts, ",local", sizeof(opts));
if (flags & MNT_QUOTA)
strlcat(opts, ",quota", sizeof(opts));
if (flags & MNT_ROOTFS)
strlcat(opts, ",rootfs", sizeof(opts));
if (flags & MNT_DOVOLFS)
strlcat(opts, ",dovolfs", sizeof(opts));
if (flags & MNT_DONTBROWSE)
strlcat(opts, ",dontbrowse", sizeof(opts));
if (flags & MNT_IGNORE_OWNERSHIP)
strlcat(opts, ",ignore-ownership", sizeof(opts));
if (flags & MNT_AUTOMOUNTED)
strlcat(opts, ",automounted", sizeof(opts));
if (flags & MNT_JOURNALED)
strlcat(opts, ",journaled", sizeof(opts));
if (flags & MNT_NOUSERXATTR)
strlcat(opts, ",nouserxattr", sizeof(opts));
if (flags & MNT_DEFWRITE)
strlcat(opts, ",defwrite", sizeof(opts));
if (flags & MNT_MULTILABEL)
strlcat(opts, ",multilabel", sizeof(opts));
if (flags & MNT_NOATIME)
strlcat(opts, ",noatime", sizeof(opts));
if (flags & MNT_UPDATE)
strlcat(opts, ",update", sizeof(opts));
if (flags & MNT_RELOAD)
strlcat(opts, ",reload", sizeof(opts));
if (flags & MNT_FORCE)
strlcat(opts, ",force", sizeof(opts));
if (flags & MNT_CMDFLAGS)
strlcat(opts, ",cmdflags", sizeof(opts));
py_dev = PyUnicode_DecodeFSDefault(fs[i].f_mntfromname);
if (! py_dev)
goto error;
py_mountp = PyUnicode_DecodeFSDefault(fs[i].f_mntonname);
if (! py_mountp)
goto error;
py_tuple = Py_BuildValue(
"(OOss)",
py_dev, // device
py_mountp, // mount point
fs[i].f_fstypename, // fs type
opts); // options
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_dev);
Py_CLEAR(py_mountp);
Py_CLEAR(py_tuple);
}
free(fs);
return py_retlist;
error:
Py_XDECREF(py_dev);
Py_XDECREF(py_mountp);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (fs != NULL)
free(fs);
return NULL;
}
PyObject *
psutil_disk_usage_used(PyObject *self, PyObject *args) {
PyObject *py_default_value;
PyObject *py_mount_point_bytes = NULL;
char* mount_point;
#if PY_MAJOR_VERSION >= 3
if (!PyArg_ParseTuple(args, "O&O", PyUnicode_FSConverter, &py_mount_point_bytes, &py_default_value)) {
return NULL;
}
mount_point = PyBytes_AsString(py_mount_point_bytes);
if (NULL == mount_point) {
Py_XDECREF(py_mount_point_bytes);
return NULL;
}
#else
if (!PyArg_ParseTuple(args, "sO", &mount_point, &py_default_value)) {
return NULL;
}
#endif
#ifdef ATTR_VOL_SPACEUSED
/* Call getattrlist(ATTR_VOL_SPACEUSED) to get used space info. */
int ret;
struct {
uint32_t size;
uint64_t spaceused;
} __attribute__((aligned(4), packed)) attrbuf = {0};
struct attrlist attrs = {0};
attrs.bitmapcount = ATTR_BIT_MAP_COUNT;
attrs.volattr = ATTR_VOL_INFO | ATTR_VOL_SPACEUSED;
Py_BEGIN_ALLOW_THREADS
ret = getattrlist(mount_point, &attrs, &attrbuf, sizeof(attrbuf), 0);
Py_END_ALLOW_THREADS
if (ret == 0) {
Py_XDECREF(py_mount_point_bytes);
return PyLong_FromUnsignedLongLong(attrbuf.spaceused);
}
psutil_debug("getattrlist(ATTR_VOL_SPACEUSED) failed, fall-back to default value");
#endif
Py_XDECREF(py_mount_point_bytes);
Py_INCREF(py_default_value);
return py_default_value;
}
/*
* Return a Python dict of tuples for disk I/O information
*/
PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
CFDictionaryRef parent_dict;
CFDictionaryRef props_dict;
CFDictionaryRef stats_dict;
io_registry_entry_t parent;
io_registry_entry_t disk;
io_iterator_t disk_list;
PyObject *py_disk_info = NULL;
PyObject *py_retdict = PyDict_New();
if (py_retdict == NULL)
return NULL;
// Get list of disks
if (IOServiceGetMatchingServices(kIOMasterPortDefault,
IOServiceMatching(kIOMediaClass),
&disk_list) != kIOReturnSuccess) {
PyErr_SetString(
PyExc_RuntimeError, "unable to get the list of disks.");
goto error;
}
// Iterate over disks
while ((disk = IOIteratorNext(disk_list)) != 0) {
py_disk_info = NULL;
parent_dict = NULL;
props_dict = NULL;
stats_dict = NULL;
if (IORegistryEntryGetParentEntry(disk, kIOServicePlane, &parent)
!= kIOReturnSuccess) {
PyErr_SetString(PyExc_RuntimeError,
"unable to get the disk's parent.");
IOObjectRelease(disk);
goto error;
}
if (IOObjectConformsTo(parent, "IOBlockStorageDriver")) {
if (IORegistryEntryCreateCFProperties(
disk,
(CFMutableDictionaryRef *) &parent_dict,
kCFAllocatorDefault,
kNilOptions
) != kIOReturnSuccess)
{
PyErr_SetString(PyExc_RuntimeError,
"unable to get the parent's properties.");
IOObjectRelease(disk);
IOObjectRelease(parent);
goto error;
}
if (IORegistryEntryCreateCFProperties(
parent,
(CFMutableDictionaryRef *) &props_dict,
kCFAllocatorDefault,
kNilOptions
) != kIOReturnSuccess)
{
PyErr_SetString(PyExc_RuntimeError,
"unable to get the disk properties.");
CFRelease(props_dict);
IOObjectRelease(disk);
IOObjectRelease(parent);
goto error;
}
const int kMaxDiskNameSize = 64;
CFStringRef disk_name_ref = (CFStringRef)CFDictionaryGetValue(
parent_dict, CFSTR(kIOBSDNameKey));
char disk_name[kMaxDiskNameSize];
CFStringGetCString(disk_name_ref,
disk_name,
kMaxDiskNameSize,
CFStringGetSystemEncoding());
stats_dict = (CFDictionaryRef)CFDictionaryGetValue(
props_dict, CFSTR(kIOBlockStorageDriverStatisticsKey));
if (stats_dict == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"Unable to get disk stats.");
goto error;
}
CFNumberRef number;
int64_t reads = 0;
int64_t writes = 0;
int64_t read_bytes = 0;
int64_t write_bytes = 0;
int64_t read_time = 0;
int64_t write_time = 0;
// Get disk reads/writes
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsReadsKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &reads);
}
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsWritesKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &writes);
}
// Get disk bytes read/written
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &read_bytes);
}
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &write_bytes);
}
// Get disk time spent reading/writing (nanoseconds)
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsTotalReadTimeKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &read_time);
}
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsTotalWriteTimeKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &write_time);
}
// Read/Write time on macOS comes back in nanoseconds and in psutil
// we've standardized on milliseconds so do the conversion.
py_disk_info = Py_BuildValue(
"(KKKKKK)",
reads,
writes,
read_bytes,
write_bytes,
read_time / 1000 / 1000,
write_time / 1000 / 1000);
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, disk_name, py_disk_info))
goto error;
Py_CLEAR(py_disk_info);
CFRelease(parent_dict);
IOObjectRelease(parent);
CFRelease(props_dict);
IOObjectRelease(disk);
}
}
IOObjectRelease (disk_list);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
return NULL;
}
| 12,376 | 31.743386 | 106 | c |
psutil | psutil-master/psutil/arch/osx/disk.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_disk_io_counters(PyObject *self, PyObject *args);
PyObject *psutil_disk_partitions(PyObject *self, PyObject *args);
PyObject *psutil_disk_usage_used(PyObject *self, PyObject *args);
| 406 | 32.916667 | 73 | h |
psutil | psutil-master/psutil/arch/osx/mem.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// System memory related functions. Original code was refactored and moved
// from psutil/_psutil_osx.c in 2023. This is the GIT blame before the move:
// https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_osx.c
#include <Python.h>
#include <mach/host_info.h>
#include <sys/sysctl.h>
#include <mach/mach.h>
#include "../../_psutil_posix.h"
static int
psutil_sys_vminfo(vm_statistics_data_t *vmstat) {
kern_return_t ret;
mach_msg_type_number_t count = sizeof(*vmstat) / sizeof(integer_t);
mach_port_t mport = mach_host_self();
ret = host_statistics(mport, HOST_VM_INFO, (host_info_t)vmstat, &count);
if (ret != KERN_SUCCESS) {
PyErr_Format(
PyExc_RuntimeError,
"host_statistics(HOST_VM_INFO) syscall failed: %s",
mach_error_string(ret));
return 0;
}
mach_port_deallocate(mach_task_self(), mport);
return 1;
}
/*
* Return system virtual memory stats.
* See:
* https://opensource.apple.com/source/system_cmds/system_cmds-790/
* vm_stat.tproj/vm_stat.c.auto.html
*/
PyObject *
psutil_virtual_mem(PyObject *self, PyObject *args) {
int mib[2];
uint64_t total;
size_t len = sizeof(total);
vm_statistics_data_t vm;
long pagesize = psutil_getpagesize();
// physical mem
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
// This is also available as sysctlbyname("hw.memsize").
if (sysctl(mib, 2, &total, &len, NULL, 0)) {
if (errno != 0)
PyErr_SetFromErrno(PyExc_OSError);
else
PyErr_Format(
PyExc_RuntimeError, "sysctl(HW_MEMSIZE) syscall failed");
return NULL;
}
// vm
if (!psutil_sys_vminfo(&vm))
return NULL;
return Py_BuildValue(
"KKKKKK",
total,
(unsigned long long) vm.active_count * pagesize, // active
(unsigned long long) vm.inactive_count * pagesize, // inactive
(unsigned long long) vm.wire_count * pagesize, // wired
(unsigned long long) vm.free_count * pagesize, // free
(unsigned long long) vm.speculative_count * pagesize // speculative
);
}
/*
* Return stats about swap memory.
*/
PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
int mib[2];
size_t size;
struct xsw_usage totals;
vm_statistics_data_t vmstat;
long pagesize = psutil_getpagesize();
mib[0] = CTL_VM;
mib[1] = VM_SWAPUSAGE;
size = sizeof(totals);
if (sysctl(mib, 2, &totals, &size, NULL, 0) == -1) {
if (errno != 0)
PyErr_SetFromErrno(PyExc_OSError);
else
PyErr_Format(
PyExc_RuntimeError, "sysctl(VM_SWAPUSAGE) syscall failed");
return NULL;
}
if (!psutil_sys_vminfo(&vmstat))
return NULL;
return Py_BuildValue(
"LLLKK",
totals.xsu_total,
totals.xsu_used,
totals.xsu_avail,
(unsigned long long)vmstat.pageins * pagesize,
(unsigned long long)vmstat.pageouts * pagesize);
}
| 3,221 | 27.263158 | 76 | c |
psutil | psutil-master/psutil/arch/osx/mem.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_swap_mem(PyObject *self, PyObject *args);
PyObject *psutil_virtual_mem(PyObject *self, PyObject *args);
| 328 | 28.909091 | 73 | h |
psutil | psutil-master/psutil/arch/osx/net.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// Networks related functions. Original code was refactored and moved
// from psutil/_psutil_osx.c in 2023. This is the GIT blame before the move:
// https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_osx.c
#include <Python.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include "../../_psutil_common.h"
PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args) {
char *buf = NULL, *lim, *next;
struct if_msghdr *ifm;
int mib[6];
mib[0] = CTL_NET; // networking subsystem
mib[1] = PF_ROUTE; // type of information
mib[2] = 0; // protocol (IPPROTO_xxx)
mib[3] = 0; // address family
mib[4] = NET_RT_IFLIST2; // operation
mib[5] = 0;
size_t len;
PyObject *py_ifc_info = NULL;
PyObject *py_retdict = PyDict_New();
if (py_retdict == NULL)
return NULL;
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
buf = malloc(len);
if (buf == NULL) {
PyErr_NoMemory();
goto error;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
lim = buf + len;
for (next = buf; next < lim; ) {
ifm = (struct if_msghdr *)next;
next += ifm->ifm_msglen;
if (ifm->ifm_type == RTM_IFINFO2) {
py_ifc_info = NULL;
struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm;
struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
char ifc_name[32];
strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);
ifc_name[sdl->sdl_nlen] = 0;
py_ifc_info = Py_BuildValue(
"(KKKKKKKi)",
if2m->ifm_data.ifi_obytes,
if2m->ifm_data.ifi_ibytes,
if2m->ifm_data.ifi_opackets,
if2m->ifm_data.ifi_ipackets,
if2m->ifm_data.ifi_ierrors,
if2m->ifm_data.ifi_oerrors,
if2m->ifm_data.ifi_iqdrops,
0); // dropout not supported
if (!py_ifc_info)
goto error;
if (PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info))
goto error;
Py_CLEAR(py_ifc_info);
}
else {
continue;
}
}
free(buf);
return py_retdict;
error:
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (buf != NULL)
free(buf);
return NULL;
}
| 2,807 | 26.529412 | 76 | c |
psutil | psutil-master/psutil/arch/osx/net.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_net_io_counters(PyObject *self, PyObject *args);
| 273 | 26.4 | 73 | h |
psutil | psutil-master/psutil/arch/osx/proc.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// Process related functions. Original code was moved in here from
// psutil/_psutil_osx.c and psutil/arc/osx/process_info.c in 2023.
// For reference, here's the GIT blame history before the move:
// https://github.com/giampaolo/psutil/blame/59504a5/psutil/_psutil_osx.c
// https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/arch/osx/process_info.c
#include <Python.h>
#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/sysctl.h>
#include <libproc.h>
#include <sys/proc_info.h>
#include <sys/sysctl.h>
#include <netinet/tcp_fsm.h>
#include <arpa/inet.h>
#include <pwd.h>
#include <unistd.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <mach/shared_region.h>
#include <mach-o/loader.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
typedef struct kinfo_proc kinfo_proc;
// ====================================================================
// --- utils
// ====================================================================
/*
* Returns a list of all BSD processes on the system. This routine
* allocates the list and puts it in *procList and a count of the
* number of entries in *procCount. You are responsible for freeing
* this list (use "free" from System framework).
* On success, the function returns 0.
* On error, the function returns a BSD errno value.
*/
static int
psutil_get_proc_list(kinfo_proc **procList, size_t *procCount) {
int mib[3];
size_t size, size2;
void *ptr;
int err;
int lim = 8; // some limit
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_ALL;
*procCount = 0;
/*
* We start by calling sysctl with ptr == NULL and size == 0.
* That will succeed, and set size to the appropriate length.
* We then allocate a buffer of at least that size and call
* sysctl with that buffer. If that succeeds, we're done.
* If that call fails with ENOMEM, we throw the buffer away
* and try again.
* Note that the loop calls sysctl with NULL again. This is
* is necessary because the ENOMEM failure case sets size to
* the amount of data returned, not the amount of data that
* could have been returned.
*/
while (lim-- > 0) {
size = 0;
if (sysctl((int *)mib, 3, NULL, &size, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ALL)");
return 1;
}
size2 = size + (size >> 3); // add some
if (size2 > size) {
ptr = malloc(size2);
if (ptr == NULL)
ptr = malloc(size);
else
size = size2;
}
else {
ptr = malloc(size);
}
if (ptr == NULL) {
PyErr_NoMemory();
return 1;
}
if (sysctl((int *)mib, 3, ptr, &size, NULL, 0) == -1) {
err = errno;
free(ptr);
if (err != ENOMEM) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ALL)");
return 1;
}
}
else {
*procList = (kinfo_proc *)ptr;
*procCount = size / sizeof(kinfo_proc);
if (procCount <= 0) {
PyErr_Format(PyExc_RuntimeError, "no PIDs found");
return 1;
}
return 0; // success
}
}
PyErr_Format(PyExc_RuntimeError, "couldn't collect PIDs list");
return 1;
}
// Read the maximum argument size for processes
static int
psutil_sysctl_argmax() {
int argmax;
int mib[2];
size_t size = sizeof(argmax);
mib[0] = CTL_KERN;
mib[1] = KERN_ARGMAX;
if (sysctl(mib, 2, &argmax, &size, NULL, 0) == 0)
return argmax;
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_ARGMAX)");
return 0;
}
// Read process argument space.
static int
psutil_sysctl_procargs(pid_t pid, char *procargs, size_t *argmax) {
int mib[3];
mib[0] = CTL_KERN;
mib[1] = KERN_PROCARGS2;
mib[2] = pid;
if (sysctl(mib, 3, procargs, argmax, NULL, 0) < 0) {
if (psutil_pid_exists(pid) == 0) {
NoSuchProcess("psutil_pid_exists -> 0");
return 1;
}
// In case of zombie process we'll get EINVAL. We translate it
// to NSP and _psosx.py will translate it to ZP.
if (errno == EINVAL) {
psutil_debug("sysctl(KERN_PROCARGS2) -> EINVAL translated to NSP");
NoSuchProcess("sysctl(KERN_PROCARGS2) -> EINVAL");
return 1;
}
// There's nothing we can do other than raising AD.
if (errno == EIO) {
psutil_debug("sysctl(KERN_PROCARGS2) -> EIO translated to AD");
AccessDenied("sysctl(KERN_PROCARGS2) -> EIO");
return 1;
}
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROCARGS2)");
return 1;
}
return 0;
}
static int
psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp) {
int mib[4];
size_t len;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = pid;
// fetch the info with sysctl()
len = sizeof(struct kinfo_proc);
// now read the data from sysctl
if (sysctl(mib, 4, kp, &len, NULL, 0) == -1) {
// raise an exception and throw errno as the error
PyErr_SetFromOSErrnoWithSyscall("sysctl");
return -1;
}
// sysctl succeeds but len is zero, happens when process has gone away
if (len == 0) {
NoSuchProcess("sysctl(kinfo_proc), len == 0");
return -1;
}
return 0;
}
/*
* A wrapper around proc_pidinfo().
* https://opensource.apple.com/source/xnu/xnu-2050.7.9/bsd/kern/proc_info.c
* Returns 0 on failure.
*/
static int
psutil_proc_pidinfo(pid_t pid, int flavor, uint64_t arg, void *pti, int size) {
errno = 0;
int ret;
ret = proc_pidinfo(pid, flavor, arg, pti, size);
if (ret <= 0) {
psutil_raise_for_pid(pid, "proc_pidinfo()");
return 0;
}
if ((unsigned long)ret < sizeof(pti)) {
psutil_raise_for_pid(
pid, "proc_pidinfo() return size < sizeof(struct_pointer)");
return 0;
}
return ret;
}
/*
* A wrapper around task_for_pid() which sucks big time:
* - it's not documented
* - errno is set only sometimes
* - sometimes errno is ENOENT (?!?)
* - for PIDs != getpid() or PIDs which are not members of the procmod
* it requires root
* As such we can only guess what the heck went wrong and fail either
* with NoSuchProcess or giveup with AccessDenied.
* Here's some history:
* https://github.com/giampaolo/psutil/issues/1181
* https://github.com/giampaolo/psutil/issues/1209
* https://github.com/giampaolo/psutil/issues/1291#issuecomment-396062519
*/
static int
psutil_task_for_pid(pid_t pid, mach_port_t *task)
{
// See: https://github.com/giampaolo/psutil/issues/1181
kern_return_t err = KERN_SUCCESS;
err = task_for_pid(mach_task_self(), pid, task);
if (err != KERN_SUCCESS) {
if (psutil_pid_exists(pid) == 0)
NoSuchProcess("task_for_pid");
// Now done in Python.
// else if (psutil_is_zombie(pid) == 1)
// PyErr_SetString(ZombieProcessError,
// "task_for_pid -> psutil_is_zombie -> 1");
else {
psutil_debug(
"task_for_pid() failed (pid=%ld, err=%i, errno=%i, msg='%s'); "
"setting AccessDenied()",
(long)pid, err, errno, mach_error_string(err));
AccessDenied("task_for_pid");
}
return 1;
}
return 0;
}
/*
* A wrapper around proc_pidinfo(PROC_PIDLISTFDS), which dynamically sets
* the buffer size.
*/
static struct proc_fdinfo*
psutil_proc_list_fds(pid_t pid, int *num_fds) {
int ret;
int fds_size = 0;
int max_size = 24 * 1024 * 1024; // 24M
struct proc_fdinfo *fds_pointer = NULL;
errno = 0;
ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
if (ret <= 0) {
psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 1/2");
goto error;
}
while (1) {
if (ret > fds_size) {
while (ret > fds_size) {
fds_size += PROC_PIDLISTFD_SIZE * 32;
if (fds_size > max_size) {
PyErr_Format(PyExc_RuntimeError,
"prevent malloc() to allocate > 24M");
goto error;
}
}
if (fds_pointer != NULL) {
free(fds_pointer);
}
fds_pointer = malloc(fds_size);
if (fds_pointer == NULL) {
PyErr_NoMemory();
goto error;
}
}
errno = 0;
ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds_pointer, fds_size);
if (ret <= 0) {
psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 2/2");
goto error;
}
if (ret + (int)PROC_PIDLISTFD_SIZE >= fds_size) {
psutil_debug("PROC_PIDLISTFDS: make room for 1 extra fd");
ret = fds_size + (int)PROC_PIDLISTFD_SIZE;
continue;
}
break;
}
*num_fds = (ret / (int)PROC_PIDLISTFD_SIZE);
return fds_pointer;
error:
if (fds_pointer != NULL)
free(fds_pointer);
return NULL;
}
// ====================================================================
// --- Python APIs
// ====================================================================
/*
* Return a Python list of all the PIDs running on the system.
*/
PyObject *
psutil_pids(PyObject *self, PyObject *args) {
kinfo_proc *proclist = NULL;
kinfo_proc *orig_address = NULL;
size_t num_processes;
size_t idx;
PyObject *py_pid = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (psutil_get_proc_list(&proclist, &num_processes) != 0)
goto error;
// save the address of proclist so we can free it later
orig_address = proclist;
for (idx = 0; idx < num_processes; idx++) {
py_pid = PyLong_FromPid(proclist->kp_proc.p_pid);
if (! py_pid)
goto error;
if (PyList_Append(py_retlist, py_pid))
goto error;
Py_CLEAR(py_pid);
proclist++;
}
free(orig_address);
return py_retlist;
error:
Py_XDECREF(py_pid);
Py_DECREF(py_retlist);
if (orig_address != NULL)
free(orig_address);
return NULL;
}
/*
* Return multiple process info as a Python tuple in one shot by
* using sysctl() and filling up a kinfo_proc struct.
* It should be possible to do this for all processes without
* incurring into permission (EPERM) errors.
* This will also succeed for zombie processes returning correct
* information.
*/
PyObject *
psutil_proc_kinfo_oneshot(PyObject *self, PyObject *args) {
pid_t pid;
struct kinfo_proc kp;
PyObject *py_name;
PyObject *py_retlist;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_get_kinfo_proc(pid, &kp) == -1)
return NULL;
py_name = PyUnicode_DecodeFSDefault(kp.kp_proc.p_comm);
if (! py_name) {
// Likely a decoding error. We don't want to fail the whole
// operation. The python module may retry with proc_name().
PyErr_Clear();
py_name = Py_None;
}
py_retlist = Py_BuildValue(
_Py_PARSE_PID "llllllidiO",
kp.kp_eproc.e_ppid, // (pid_t) ppid
(long)kp.kp_eproc.e_pcred.p_ruid, // (long) real uid
(long)kp.kp_eproc.e_ucred.cr_uid, // (long) effective uid
(long)kp.kp_eproc.e_pcred.p_svuid, // (long) saved uid
(long)kp.kp_eproc.e_pcred.p_rgid, // (long) real gid
(long)kp.kp_eproc.e_ucred.cr_groups[0], // (long) effective gid
(long)kp.kp_eproc.e_pcred.p_svgid, // (long) saved gid
kp.kp_eproc.e_tdev, // (int) tty nr
PSUTIL_TV2DOUBLE(kp.kp_proc.p_starttime), // (double) create time
(int)kp.kp_proc.p_stat, // (int) status
py_name // (pystr) name
);
if (py_retlist != NULL) {
// XXX shall we decref() also in case of Py_BuildValue() error?
Py_DECREF(py_name);
}
return py_retlist;
}
/*
* Return multiple process info as a Python tuple in one shot by
* using proc_pidinfo(PROC_PIDTASKINFO) and filling a proc_taskinfo
* struct.
* Contrarily from proc_kinfo above this function will fail with
* EACCES for PIDs owned by another user and with ESRCH for zombie
* processes.
*/
PyObject *
psutil_proc_pidtaskinfo_oneshot(PyObject *self, PyObject *args) {
pid_t pid;
struct proc_taskinfo pti;
uint64_t total_user;
uint64_t total_system;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti)) <= 0)
return NULL;
total_user = pti.pti_total_user * PSUTIL_MACH_TIMEBASE_INFO.numer;
total_user /= PSUTIL_MACH_TIMEBASE_INFO.denom;
total_system = pti.pti_total_system * PSUTIL_MACH_TIMEBASE_INFO.numer;
total_system /= PSUTIL_MACH_TIMEBASE_INFO.denom;
return Py_BuildValue(
"(ddKKkkkk)",
(float)total_user / 1000000000.0, // (float) cpu user time
(float)total_system / 1000000000.0, // (float) cpu sys time
// Note about memory: determining other mem stats on macOS is a mess:
// http://www.opensource.apple.com/source/top/top-67/libtop.c?txt
// I just give up.
// struct proc_regioninfo pri;
// psutil_proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, sizeof(pri))
pti.pti_resident_size, // (uns long long) rss
pti.pti_virtual_size, // (uns long long) vms
pti.pti_faults, // (uns long) number of page faults (pages)
pti.pti_pageins, // (uns long) number of actual pageins (pages)
pti.pti_threadnum, // (uns long) num threads
// Unvoluntary value seems not to be available;
// pti.pti_csw probably refers to the sum of the two;
// getrusage() numbers seems to confirm this theory.
pti.pti_csw // (uns long) voluntary ctx switches
);
}
/*
* Return process name from kinfo_proc as a Python string.
*/
PyObject *
psutil_proc_name(PyObject *self, PyObject *args) {
pid_t pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_get_kinfo_proc(pid, &kp) == -1)
return NULL;
return PyUnicode_DecodeFSDefault(kp.kp_proc.p_comm);
}
/*
* Return process current working directory.
* Raises NSP in case of zombie process.
*/
PyObject *
psutil_proc_cwd(PyObject *self, PyObject *args) {
pid_t pid;
struct proc_vnodepathinfo pathinfo;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_proc_pidinfo(
pid, PROC_PIDVNODEPATHINFO, 0, &pathinfo, sizeof(pathinfo)) <= 0)
{
return NULL;
}
return PyUnicode_DecodeFSDefault(pathinfo.pvi_cdir.vip_path);
}
/*
* Return path of the process executable.
*/
PyObject *
psutil_proc_exe(PyObject *self, PyObject *args) {
pid_t pid;
char buf[PATH_MAX];
int ret;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
errno = 0;
ret = proc_pidpath(pid, &buf, sizeof(buf));
if (ret == 0) {
if (pid == 0) {
AccessDenied("automatically set for PID 0");
return NULL;
}
else if (errno == ENOENT) {
// It may happen (file not found error) if the process is
// still alive but the executable which launched it got
// deleted, see:
// https://github.com/giampaolo/psutil/issues/1738
return Py_BuildValue("s", "");
}
else {
psutil_raise_for_pid(pid, "proc_pidpath()");
return NULL;
}
}
return PyUnicode_DecodeFSDefault(buf);
}
/*
* Indicates if the given virtual address on the given architecture is in the
* shared VM region.
*/
static bool
psutil_in_shared_region(mach_vm_address_t addr, cpu_type_t type) {
mach_vm_address_t base;
mach_vm_address_t size;
switch (type) {
case CPU_TYPE_ARM:
base = SHARED_REGION_BASE_ARM;
size = SHARED_REGION_SIZE_ARM;
break;
case CPU_TYPE_I386:
base = SHARED_REGION_BASE_I386;
size = SHARED_REGION_SIZE_I386;
break;
case CPU_TYPE_X86_64:
base = SHARED_REGION_BASE_X86_64;
size = SHARED_REGION_SIZE_X86_64;
break;
default:
return false;
}
return base <= addr && addr < (base + size);
}
/*
* Returns the USS (unique set size) of the process. Reference:
* https://dxr.mozilla.org/mozilla-central/source/xpcom/base/
* nsMemoryReporterManager.cpp
*/
PyObject *
psutil_proc_memory_uss(PyObject *self, PyObject *args) {
pid_t pid;
size_t len;
cpu_type_t cpu_type;
size_t private_pages = 0;
mach_vm_size_t size = 0;
mach_msg_type_number_t info_count = VM_REGION_TOP_INFO_COUNT;
kern_return_t kr;
long pagesize = psutil_getpagesize();
mach_vm_address_t addr = MACH_VM_MIN_ADDRESS;
mach_port_t task = MACH_PORT_NULL;
vm_region_top_info_data_t info;
mach_port_t object_name;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_task_for_pid(pid, &task) != 0)
return NULL;
len = sizeof(cpu_type);
if (sysctlbyname("sysctl.proc_cputype", &cpu_type, &len, NULL, 0) != 0) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('sysctl.proc_cputype')");
}
// Roughly based on libtop_update_vm_regions in
// http://www.opensource.apple.com/source/top/top-100.1.2/libtop.c
for (addr = 0; ; addr += size) {
kr = mach_vm_region(
task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info,
&info_count, &object_name);
if (kr == KERN_INVALID_ADDRESS) {
// Done iterating VM regions.
break;
}
else if (kr != KERN_SUCCESS) {
PyErr_Format(
PyExc_RuntimeError,
"mach_vm_region(VM_REGION_TOP_INFO) syscall failed");
return NULL;
}
if (psutil_in_shared_region(addr, cpu_type) &&
info.share_mode != SM_PRIVATE) {
continue;
}
switch (info.share_mode) {
#ifdef SM_LARGE_PAGE
case SM_LARGE_PAGE:
// NB: Large pages are not shareable and always resident.
#endif
case SM_PRIVATE:
private_pages += info.private_pages_resident;
private_pages += info.shared_pages_resident;
break;
case SM_COW:
private_pages += info.private_pages_resident;
if (info.ref_count == 1) {
// Treat copy-on-write pages as private if they only
// have one reference.
private_pages += info.shared_pages_resident;
}
break;
case SM_SHARED:
default:
break;
}
}
mach_port_deallocate(mach_task_self(), task);
return Py_BuildValue("K", private_pages * pagesize);
}
/*
* Return process threads
*/
PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
pid_t pid;
int err, ret;
kern_return_t kr;
unsigned int info_count = TASK_BASIC_INFO_COUNT;
mach_port_t task = MACH_PORT_NULL;
struct task_basic_info tasks_info;
thread_act_port_array_t thread_list = NULL;
thread_info_data_t thinfo_basic;
thread_basic_info_t basic_info_th;
mach_msg_type_number_t thread_count, thread_info_count, j;
PyObject *py_tuple = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
if (psutil_task_for_pid(pid, &task) != 0)
goto error;
info_count = TASK_BASIC_INFO_COUNT;
err = task_info(task, TASK_BASIC_INFO, (task_info_t)&tasks_info,
&info_count);
if (err != KERN_SUCCESS) {
// errcode 4 is "invalid argument" (access denied)
if (err == 4) {
AccessDenied("task_info(TASK_BASIC_INFO)");
}
else {
// otherwise throw a runtime error with appropriate error code
PyErr_Format(PyExc_RuntimeError,
"task_info(TASK_BASIC_INFO) syscall failed");
}
goto error;
}
err = task_threads(task, &thread_list, &thread_count);
if (err != KERN_SUCCESS) {
PyErr_Format(PyExc_RuntimeError, "task_threads() syscall failed");
goto error;
}
for (j = 0; j < thread_count; j++) {
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo_basic, &thread_info_count);
if (kr != KERN_SUCCESS) {
PyErr_Format(PyExc_RuntimeError,
"thread_info(THREAD_BASIC_INFO) syscall failed");
goto error;
}
basic_info_th = (thread_basic_info_t)thinfo_basic;
py_tuple = Py_BuildValue(
"Iff",
j + 1,
basic_info_th->user_time.seconds + \
(float)basic_info_th->user_time.microseconds / 1000000.0,
basic_info_th->system_time.seconds + \
(float)basic_info_th->system_time.microseconds / 1000000.0
);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
ret = vm_deallocate(task, (vm_address_t)thread_list,
thread_count * sizeof(int));
if (ret != KERN_SUCCESS)
PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
mach_port_deallocate(mach_task_self(), task);
return py_retlist;
error:
if (task != MACH_PORT_NULL)
mach_port_deallocate(mach_task_self(), task);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (thread_list != NULL) {
ret = vm_deallocate(task, (vm_address_t)thread_list,
thread_count * sizeof(int));
if (ret != KERN_SUCCESS)
PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
}
return NULL;
}
/*
* Return process open files as a Python tuple.
* References:
* - lsof source code: http://goo.gl/SYW79 and http://goo.gl/m78fd
* - /usr/include/sys/proc_info.h
*/
PyObject *
psutil_proc_open_files(PyObject *self, PyObject *args) {
pid_t pid;
int num_fds;
int i;
unsigned long nb;
struct proc_fdinfo *fds_pointer = NULL;
struct proc_fdinfo *fdp_pointer;
struct vnode_fdinfowithpath vi;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_path = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
// see: https://github.com/giampaolo/psutil/issues/2116
if (pid == 0)
return py_retlist;
fds_pointer = psutil_proc_list_fds(pid, &num_fds);
if (fds_pointer == NULL)
goto error;
for (i = 0; i < num_fds; i++) {
fdp_pointer = &fds_pointer[i];
if (fdp_pointer->proc_fdtype == PROX_FDTYPE_VNODE) {
errno = 0;
nb = proc_pidfdinfo((pid_t)pid,
fdp_pointer->proc_fd,
PROC_PIDFDVNODEPATHINFO,
&vi,
sizeof(vi));
// --- errors checking
if ((nb <= 0) || nb < sizeof(vi)) {
if ((errno == ENOENT) || (errno == EBADF)) {
// no such file or directory or bad file descriptor;
// let's assume the file has been closed or removed
continue;
}
else {
psutil_raise_for_pid(
pid, "proc_pidinfo(PROC_PIDFDVNODEPATHINFO)");
goto error;
}
}
// --- /errors checking
// --- construct python list
py_path = PyUnicode_DecodeFSDefault(vi.pvip.vip_path);
if (! py_path)
goto error;
py_tuple = Py_BuildValue(
"(Oi)",
py_path,
(int)fdp_pointer->proc_fd);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
Py_CLEAR(py_path);
// --- /construct python list
}
}
free(fds_pointer);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_path);
Py_DECREF(py_retlist);
if (fds_pointer != NULL)
free(fds_pointer);
return NULL; // exception has already been set earlier
}
/*
* Return process TCP and UDP connections as a list of tuples.
* Raises NSP in case of zombie process.
* References:
* - lsof source code: http://goo.gl/SYW79 and http://goo.gl/wNrC0
* - /usr/include/sys/proc_info.h
*/
PyObject *
psutil_proc_connections(PyObject *self, PyObject *args) {
pid_t pid;
int num_fds;
int i;
unsigned long nb;
struct proc_fdinfo *fds_pointer = NULL;
struct proc_fdinfo *fdp_pointer;
struct socket_fdinfo si;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
PyObject *py_af_filter = NULL;
PyObject *py_type_filter = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID "OO", &pid, &py_af_filter,
&py_type_filter)) {
goto error;
}
// see: https://github.com/giampaolo/psutil/issues/2116
if (pid == 0)
return py_retlist;
if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) {
PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
goto error;
}
fds_pointer = psutil_proc_list_fds(pid, &num_fds);
if (fds_pointer == NULL)
goto error;
for (i = 0; i < num_fds; i++) {
py_tuple = NULL;
py_laddr = NULL;
py_raddr = NULL;
fdp_pointer = &fds_pointer[i];
if (fdp_pointer->proc_fdtype == PROX_FDTYPE_SOCKET) {
errno = 0;
nb = proc_pidfdinfo(pid, fdp_pointer->proc_fd,
PROC_PIDFDSOCKETINFO, &si, sizeof(si));
// --- errors checking
if ((nb <= 0) || (nb < sizeof(si)) || (errno != 0)) {
if (errno == EBADF) {
// let's assume socket has been closed
psutil_debug("proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> "
"EBADF (ignored)");
continue;
}
else if (errno == EOPNOTSUPP) {
// may happen sometimes, see:
// https://github.com/giampaolo/psutil/issues/1512
psutil_debug("proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> "
"EOPNOTSUPP (ignored)");
continue;
}
else {
psutil_raise_for_pid(
pid, "proc_pidinfo(PROC_PIDFDSOCKETINFO)");
goto error;
}
}
// --- /errors checking
//
int fd, family, type, lport, rport, state;
// TODO: use INET6_ADDRSTRLEN instead of 200
char lip[200], rip[200];
int inseq;
PyObject *py_family;
PyObject *py_type;
fd = (int)fdp_pointer->proc_fd;
family = si.psi.soi_family;
type = si.psi.soi_type;
// apply filters
py_family = PyLong_FromLong((long)family);
inseq = PySequence_Contains(py_af_filter, py_family);
Py_DECREF(py_family);
if (inseq == 0)
continue;
py_type = PyLong_FromLong((long)type);
inseq = PySequence_Contains(py_type_filter, py_type);
Py_DECREF(py_type);
if (inseq == 0)
continue;
if ((family == AF_INET) || (family == AF_INET6)) {
if (family == AF_INET) {
inet_ntop(AF_INET,
&si.psi.soi_proto.pri_tcp.tcpsi_ini. \
insi_laddr.ina_46.i46a_addr4,
lip,
sizeof(lip));
inet_ntop(AF_INET,
&si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr. \
ina_46.i46a_addr4,
rip,
sizeof(rip));
}
else {
inet_ntop(AF_INET6,
&si.psi.soi_proto.pri_tcp.tcpsi_ini. \
insi_laddr.ina_6,
lip, sizeof(lip));
inet_ntop(AF_INET6,
&si.psi.soi_proto.pri_tcp.tcpsi_ini. \
insi_faddr.ina_6,
rip, sizeof(rip));
}
// check for inet_ntop failures
if (errno != 0) {
PyErr_SetFromOSErrnoWithSyscall("inet_ntop()");
goto error;
}
lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport);
rport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport);
if (type == SOCK_STREAM)
state = (int)si.psi.soi_proto.pri_tcp.tcpsi_state;
else
state = PSUTIL_CONN_NONE;
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", rip, rport);
else
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
// construct the python list
py_tuple = Py_BuildValue(
"(iiiNNi)", fd, family, type, py_laddr, py_raddr, state);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
else if (family == AF_UNIX) {
py_laddr = PyUnicode_DecodeFSDefault(
si.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path);
if (!py_laddr)
goto error;
py_raddr = PyUnicode_DecodeFSDefault(
si.psi.soi_proto.pri_un.unsi_caddr.ua_sun.sun_path);
if (!py_raddr)
goto error;
// construct the python list
py_tuple = Py_BuildValue(
"(iiiOOi)",
fd, family, type,
py_laddr,
py_raddr,
PSUTIL_CONN_NONE);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
Py_CLEAR(py_laddr);
Py_CLEAR(py_raddr);
}
}
}
free(fds_pointer);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
Py_DECREF(py_retlist);
if (fds_pointer != NULL)
free(fds_pointer);
return NULL;
}
/*
* Return number of file descriptors opened by process.
* Raises NSP in case of zombie process.
*/
PyObject *
psutil_proc_num_fds(PyObject *self, PyObject *args) {
pid_t pid;
int num_fds;
struct proc_fdinfo *fds_pointer;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
fds_pointer = psutil_proc_list_fds(pid, &num_fds);
if (fds_pointer == NULL)
return NULL;
free(fds_pointer);
return Py_BuildValue("i", num_fds);
}
// return process args as a python list
PyObject *
psutil_proc_cmdline(PyObject *self, PyObject *args) {
pid_t pid;
int nargs;
size_t len;
char *procargs = NULL;
char *arg_ptr;
char *arg_end;
char *curr_arg;
size_t argmax;
PyObject *py_retlist = PyList_New(0);
PyObject *py_arg = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
// special case for PID 0 (kernel_task) where cmdline cannot be fetched
if (pid == 0)
return py_retlist;
// read argmax and allocate memory for argument space.
argmax = psutil_sysctl_argmax();
if (! argmax)
goto error;
procargs = (char *)malloc(argmax);
if (NULL == procargs) {
PyErr_NoMemory();
goto error;
}
if (psutil_sysctl_procargs(pid, procargs, &argmax) != 0)
goto error;
arg_end = &procargs[argmax];
// copy the number of arguments to nargs
memcpy(&nargs, procargs, sizeof(nargs));
arg_ptr = procargs + sizeof(nargs);
len = strlen(arg_ptr);
arg_ptr += len + 1;
if (arg_ptr == arg_end) {
free(procargs);
return py_retlist;
}
// skip ahead to the first argument
for (; arg_ptr < arg_end; arg_ptr++) {
if (*arg_ptr != '\0')
break;
}
// iterate through arguments
curr_arg = arg_ptr;
while (arg_ptr < arg_end && nargs > 0) {
if (*arg_ptr++ == '\0') {
py_arg = PyUnicode_DecodeFSDefault(curr_arg);
if (! py_arg)
goto error;
if (PyList_Append(py_retlist, py_arg))
goto error;
Py_DECREF(py_arg);
// iterate to next arg and decrement # of args
curr_arg = arg_ptr;
nargs--;
}
}
free(procargs);
return py_retlist;
error:
Py_XDECREF(py_arg);
Py_XDECREF(py_retlist);
if (procargs != NULL)
free(procargs);
return NULL;
}
// Return process environment as a python string.
// On Big Sur this function returns an empty string unless:
// * kernel is DEVELOPMENT || DEBUG
// * target process is same as current_proc()
// * target process is not cs_restricted
// * SIP is off
// * caller has an entitlement
// See: https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/kern/kern_sysctl.c#L1315-L1321
PyObject *
psutil_proc_environ(PyObject *self, PyObject *args) {
pid_t pid;
int nargs;
char *procargs = NULL;
char *procenv = NULL;
char *arg_ptr;
char *arg_end;
char *env_start;
size_t argmax;
PyObject *py_ret = NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
// special case for PID 0 (kernel_task) where cmdline cannot be fetched
if (pid == 0)
goto empty;
// read argmax and allocate memory for argument space.
argmax = psutil_sysctl_argmax();
if (! argmax)
goto error;
procargs = (char *)malloc(argmax);
if (NULL == procargs) {
PyErr_NoMemory();
goto error;
}
if (psutil_sysctl_procargs(pid, procargs, &argmax) != 0)
goto error;
arg_end = &procargs[argmax];
// copy the number of arguments to nargs
memcpy(&nargs, procargs, sizeof(nargs));
// skip executable path
arg_ptr = procargs + sizeof(nargs);
arg_ptr = memchr(arg_ptr, '\0', arg_end - arg_ptr);
if (arg_ptr == NULL || arg_ptr == arg_end) {
psutil_debug(
"(arg_ptr == NULL || arg_ptr == arg_end); set environ to empty");
goto empty;
}
// skip ahead to the first argument
for (; arg_ptr < arg_end; arg_ptr++) {
if (*arg_ptr != '\0')
break;
}
// iterate through arguments
while (arg_ptr < arg_end && nargs > 0) {
if (*arg_ptr++ == '\0')
nargs--;
}
// build an environment variable block
env_start = arg_ptr;
procenv = calloc(1, arg_end - arg_ptr);
if (procenv == NULL) {
PyErr_NoMemory();
goto error;
}
while (*arg_ptr != '\0' && arg_ptr < arg_end) {
char *s = memchr(arg_ptr + 1, '\0', arg_end - arg_ptr);
if (s == NULL)
break;
memcpy(procenv + (arg_ptr - env_start), arg_ptr, s - arg_ptr);
arg_ptr = s + 1;
}
py_ret = PyUnicode_DecodeFSDefaultAndSize(
procenv, arg_ptr - env_start + 1);
if (!py_ret) {
// XXX: don't want to free() this as per:
// https://github.com/giampaolo/psutil/issues/926
// It sucks but not sure what else to do.
procargs = NULL;
goto error;
}
free(procargs);
free(procenv);
return py_ret;
empty:
if (procargs != NULL)
free(procargs);
return Py_BuildValue("s", "");
error:
Py_XDECREF(py_ret);
if (procargs != NULL)
free(procargs);
if (procenv != NULL)
free(procargs);
return NULL;
}
| 38,150 | 29.087539 | 124 | c |
psutil | psutil-master/psutil/arch/osx/proc.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_pids(PyObject *self, PyObject *args);
PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args);
PyObject *psutil_proc_connections(PyObject *self, PyObject *args);
PyObject *psutil_proc_cwd(PyObject *self, PyObject *args);
PyObject *psutil_proc_environ(PyObject *self, PyObject *args);
PyObject *psutil_proc_exe(PyObject *self, PyObject *args);
PyObject *psutil_proc_kinfo_oneshot(PyObject *self, PyObject *args);
PyObject *psutil_proc_memory_uss(PyObject *self, PyObject *args);
PyObject *psutil_proc_name(PyObject *self, PyObject *args);
PyObject *psutil_proc_num_fds(PyObject *self, PyObject *args);
PyObject *psutil_proc_open_files(PyObject *self, PyObject *args);
PyObject *psutil_proc_pidtaskinfo_oneshot(PyObject *self, PyObject *args);
PyObject *psutil_proc_threads(PyObject *self, PyObject *args);
| 1,035 | 46.090909 | 74 | h |
psutil | psutil-master/psutil/arch/osx/sensors.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// Sensors related functions. Original code was refactored and moved
// from psutil/_psutil_osx.c in 2023. This is the GIT blame before the move:
// https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_osx.c
// Original battery code:
// https://github.com/giampaolo/psutil/commit/e0df5da
#include <Python.h>
#include <IOKit/ps/IOPowerSources.h>
#include <IOKit/ps/IOPSKeys.h>
#include "../../_psutil_common.h"
PyObject *
psutil_sensors_battery(PyObject *self, PyObject *args) {
PyObject *py_tuple = NULL;
CFTypeRef power_info = NULL;
CFArrayRef power_sources_list = NULL;
CFDictionaryRef power_sources_information = NULL;
CFNumberRef capacity_ref = NULL;
CFNumberRef time_to_empty_ref = NULL;
CFStringRef ps_state_ref = NULL;
uint32_t capacity; /* units are percent */
int time_to_empty; /* units are minutes */
int is_power_plugged;
power_info = IOPSCopyPowerSourcesInfo();
if (!power_info) {
PyErr_SetString(PyExc_RuntimeError,
"IOPSCopyPowerSourcesInfo() syscall failed");
goto error;
}
power_sources_list = IOPSCopyPowerSourcesList(power_info);
if (!power_sources_list) {
PyErr_SetString(PyExc_RuntimeError,
"IOPSCopyPowerSourcesList() syscall failed");
goto error;
}
/* Should only get one source. But in practice, check for > 0 sources */
if (!CFArrayGetCount(power_sources_list)) {
PyErr_SetString(PyExc_NotImplementedError, "no battery");
goto error;
}
power_sources_information = IOPSGetPowerSourceDescription(
power_info, CFArrayGetValueAtIndex(power_sources_list, 0));
capacity_ref = (CFNumberRef) CFDictionaryGetValue(
power_sources_information, CFSTR(kIOPSCurrentCapacityKey));
if (!CFNumberGetValue(capacity_ref, kCFNumberSInt32Type, &capacity)) {
PyErr_SetString(PyExc_RuntimeError,
"No battery capacity infomration in power sources info");
goto error;
}
ps_state_ref = (CFStringRef) CFDictionaryGetValue(
power_sources_information, CFSTR(kIOPSPowerSourceStateKey));
is_power_plugged = CFStringCompare(
ps_state_ref, CFSTR(kIOPSACPowerValue), 0)
== kCFCompareEqualTo;
time_to_empty_ref = (CFNumberRef) CFDictionaryGetValue(
power_sources_information, CFSTR(kIOPSTimeToEmptyKey));
if (!CFNumberGetValue(time_to_empty_ref,
kCFNumberIntType, &time_to_empty)) {
/* This value is recommended for non-Apple power sources, so it's not
* an error if it doesn't exist. We'll return -1 for "unknown" */
/* A value of -1 indicates "Still Calculating the Time" also for
* apple power source */
time_to_empty = -1;
}
py_tuple = Py_BuildValue("Iii",
capacity, time_to_empty, is_power_plugged);
if (!py_tuple) {
goto error;
}
CFRelease(power_info);
CFRelease(power_sources_list);
/* Caller should NOT release power_sources_information */
return py_tuple;
error:
if (power_info)
CFRelease(power_info);
if (power_sources_list)
CFRelease(power_sources_list);
Py_XDECREF(py_tuple);
return NULL;
}
| 3,421 | 32.223301 | 77 | c |
psutil | psutil-master/psutil/arch/osx/sensors.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_sensors_battery(PyObject *self, PyObject *args);
| 273 | 26.4 | 73 | h |
psutil | psutil-master/psutil/arch/osx/sys.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// System related functions. Original code was refactored and moved
// from psutil/_psutil_osx.c in 2023. This is the GIT blame before the move:
// https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_osx.c
#include <Python.h>
#include <sys/sysctl.h>
#include <utmpx.h>
#include "../../_psutil_common.h"
PyObject *
psutil_boot_time(PyObject *self, PyObject *args) {
// fetch sysctl "kern.boottime"
static int request[2] = { CTL_KERN, KERN_BOOTTIME };
struct timeval result;
size_t result_len = sizeof result;
time_t boot_time = 0;
if (sysctl(request, 2, &result, &result_len, NULL, 0) == -1)
return PyErr_SetFromErrno(PyExc_OSError);
boot_time = result.tv_sec;
return Py_BuildValue("f", (float)boot_time);
}
PyObject *
psutil_users(PyObject *self, PyObject *args) {
struct utmpx *utx;
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_tuple = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
while ((utx = getutxent()) != NULL) {
if (utx->ut_type != USER_PROCESS)
continue;
py_username = PyUnicode_DecodeFSDefault(utx->ut_user);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(utx->ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(utx->ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"(OOOdi)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)utx->ut_tv.tv_sec, // start time
utx->ut_pid // process id
);
if (!py_tuple) {
endutxent();
goto error;
}
if (PyList_Append(py_retlist, py_tuple)) {
endutxent();
goto error;
}
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
}
endutxent();
return py_retlist;
error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
return NULL;
}
| 2,529 | 27.426966 | 76 | c |
psutil | psutil-master/psutil/arch/osx/sys.h | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Python.h>
PyObject *psutil_boot_time(PyObject *self, PyObject *args);
PyObject *psutil_users(PyObject *self, PyObject *args);
| 323 | 28.454545 | 73 | h |