Collect net_io_counters only if available
Previously this would error if `psutil.net_io_counters` failed, which
can happen in certain environments. We now check if it's available on
startup, and only collect io stats if available.
@@ -14,18 +14,25 @@ class SystemMonitor(object):
self.time = deque(maxlen=n)
self.cpu = deque(maxlen=n)
self.memory = deque(maxlen=n)
- self.read_bytes = deque(maxlen=n)
- self.write_bytes = deque(maxlen=n)
-
- self.last_time = time()
self.count = 0
- self._last_io_counters = psutil.net_io_counters()
self.quantities = {'cpu': self.cpu,
'memory': self.memory,
- 'time': self.time,
- 'read_bytes': self.read_bytes,
- 'write_bytes': self.write_bytes}
+ 'time': self.time}
+
+ try:
+ ioc = psutil.net_io_counters()
+ except Exception:
+ self._collect_net_io_counters = False
+ else:
+ self.last_time = time()
+ self.read_bytes = deque(maxlen=n)
+ self.write_bytes = deque(maxlen=n)
+ self.quantities['read_bytes'] = self.read_bytes
+ self.quantities['write_bytes'] = self.write_bytes
+ self._last_io_counters = ioc
+ self._collect_net_io_counters = True
+
if not WINDOWS:
self.num_fds = deque(maxlen=n)
self.quantities['num_fds'] = self.num_fds
@@ -33,28 +40,30 @@ class SystemMonitor(object):
def update(self):
cpu = self.proc.cpu_percent()
memory = self.proc.memory_info().rss
-
now = time()
+
+ self.cpu.append(cpu)
+ self.memory.append(memory)
+ self.time.append(now)
+ self.count += 1
+
+ result = {'cpu': cpu,
+ 'memory': memory,
+ 'time': now,
+ 'count': self.count}
+
+ if self._collect_net_io_counters:
ioc = psutil.net_io_counters()
last = self._last_io_counters
duration = now - self.last_time
read_bytes = (ioc.bytes_recv - last.bytes_recv) / (duration or 0.5)
write_bytes = (ioc.bytes_sent - last.bytes_sent) / (duration or 0.5)
- self._last_io_counters = ioc
self.last_time = now
-
- self.cpu.append(cpu)
- self.memory.append(memory)
- self.time.append(now)
-
+ self._last_io_counters = ioc
self.read_bytes.append(read_bytes)
self.write_bytes.append(write_bytes)
-
- self.count += 1
-
- result = {'cpu': cpu, 'memory': memory, 'time': now,
- 'count': self.count, 'read_bytes': read_bytes,
- 'write_bytes': write_bytes}
+ result['read_bytes'] = read_bytes
+ result['write_bytes'] = write_bytes
if not WINDOWS:
num_fds = self.proc.num_fds()
