Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import psutil raises IOError on Linux when /proc/stat is inaccessible #715

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@
RLIMIT_SIGPENDING = _psutil_linux.RLIMIT_SIGPENDING
except AttributeError:
pass
del _psutil_linux

elif sys.platform.startswith("win32"):
from . import _pswindows as _psplatform
Expand Down Expand Up @@ -1412,9 +1411,13 @@ def cpu_times(percpu=False):
else:
return _psplatform.per_cpu_times()


_last_cpu_times = cpu_times()
_last_per_cpu_times = cpu_times(percpu=True)
try:
_last_cpu_times = cpu_times()
_last_per_cpu_times = cpu_times(percpu=True)
except IOError:
from collections import namedtuple
_last_cpu_times = namedtuple('emptycpu', 'idle')(0)
_last_per_cpu_times = []


def cpu_percent(interval=None, percpu=False):
Expand Down Expand Up @@ -1522,8 +1525,8 @@ def cpu_times_percent(interval=None, percpu=False):
def calculate(t1, t2):
nums = []
all_delta = sum(t2) - sum(t1)
for field in t1._fields:
field_delta = getattr(t2, field) - getattr(t1, field)
for field in t2._fields:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why did you change from t1 to t2?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

t1 is the least-recent set of data points, so if the underlying /proc/stat file changes to provide a different number of fields (e.g. if we go from not having fields to having some fields) then t2 will have the latest and most correct set of fields.

The danger is that t1 will be missing some values, hence the default attr provided on the next line.

field_delta = getattr(t2, field) - getattr(t1, field, 0)
try:
field_perc = (100 * field_delta) / all_delta
except ZeroDivisionError:
Expand Down
10 changes: 6 additions & 4 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,13 @@ def set_scputimes_ntuple(procfs_path):
[guest_nice]]])
"""
global scputimes
with open_binary('%s/stat' % procfs_path) as f:
values = f.readline().split()[1:]
try:
with open_binary('%s/stat' % procfs_path) as f:
values = f.readline().split()[1:]
vlen = len(values)
except IOError:
vlen = 7
fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
vlen = len(values)
if vlen >= 8:
# Linux >= 2.6.11
fields.append('steal')
Expand All @@ -172,7 +175,6 @@ def set_scputimes_ntuple(procfs_path):
scputimes = namedtuple('scputimes', fields)
return scputimes


scputimes = set_scputimes_ntuple('/proc')

svmem = namedtuple(
Expand Down
75 changes: 75 additions & 0 deletions test/_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import os
import pprint
import re
import shutil
import socket
import struct
import sys
Expand Down Expand Up @@ -44,6 +45,13 @@
from test_psutil import unittest
from test_psutil import which

if PY3:
import importlib as imp
# python 3.3
if not hasattr(imp, 'reload'):
import imp
else:
import imp

# procps-ng 3.3.10 changed the output format of free
# and removed the 'buffers/cache line'
Expand Down Expand Up @@ -471,6 +479,73 @@ def test_procfs_path(self):
psutil.PROCFS_PATH = "/proc"
os.rmdir(tdir)

def test_psutil_is_reloadable(self):
imp.reload(psutil)

def test_no_procfs_for_import(self):
my_procfs = tempfile.mkdtemp()

with open(os.path.join(my_procfs, 'stat'), 'w') as f:
f.write('cpu 0 0 0 0 0 0 0 0 0 0\n')
f.write('cpu0 0 0 0 0 0 0 0 0 0 0\n')
f.write('cpu1 0 0 0 0 0 0 0 0 0 0\n')

self.assertNotAlmostEqual(psutil.cpu_percent(), 0)
self.assertNotAlmostEqual(sum(psutil.cpu_times_percent()), 0)
try:
orig_open = open

def open_mock(name, *args):
if name.startswith('/proc'):
# simulate an ENOENT
raise IOError('rejecting access to /proc')
return orig_open(name, *args)
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, side_effect=open_mock):
imp.reload(psutil)

self.assertRaises(IOError, psutil.cpu_times)
self.assertRaises(IOError, psutil.cpu_times, percpu=True)
self.assertRaises(IOError, psutil.cpu_percent)
self.assertRaises(IOError, psutil.cpu_percent, percpu=True)
self.assertRaises(IOError, psutil.cpu_times_percent)
self.assertRaises(
IOError, psutil.cpu_times_percent, percpu=True)

psutil.PROCFS_PATH = my_procfs

self.assertAlmostEqual(psutil.cpu_percent(), 0)
self.assertAlmostEqual(sum(psutil.cpu_times_percent()), 0)

# since we don't know the number of CPUs at import time,
# we awkwardly say there are none until the second call
per_cpu_percent = psutil.cpu_percent(percpu=True)
self.assertEqual(len(per_cpu_percent), 0)
self.assertAlmostEqual(sum(per_cpu_percent), 0)

# ditto awkward length
per_cpu_times_percent = psutil.cpu_times_percent(percpu=True)
self.assertEqual(len(per_cpu_times_percent), 0)
self.assertAlmostEqual(sum(map(sum, per_cpu_percent)), 0)

# much user, very busy
with open(os.path.join(my_procfs, 'stat'), 'w') as f:
f.write('cpu 1 0 0 0 0 0 0 0 0 0\n')
f.write('cpu0 1 0 0 0 0 0 0 0 0 0\n')
f.write('cpu1 1 0 0 0 0 0 0 0 0 0\n')

self.assertNotAlmostEqual(psutil.cpu_percent(), 0)
self.assertNotAlmostEqual(
sum(psutil.cpu_percent(percpu=True)), 0)
self.assertNotAlmostEqual(sum(psutil.cpu_times_percent()), 0)
self.assertNotAlmostEqual(
sum(map(sum, psutil.cpu_times_percent(percpu=True))), 0)
finally:
shutil.rmtree(my_procfs)
imp.reload(psutil)

assert psutil.PROCFS_PATH == '/proc'

# --- tests for specific kernel versions

@unittest.skipUnless(
Expand Down