-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprocstats.py
78 lines (59 loc) · 1.8 KB
/
procstats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012, Rui Carmo
Description: Utility functions for retrieving process information
License: MIT (see LICENSE.md for details)
"""
import os
import logging
import platform
import __builtin__
log = logging.getLogger()
# Module globals
openfiles = set()
oldfile = __builtin__.file
oldopen = __builtin__.open
patched = False
class _file(oldfile):
"""File wrapper"""
def __init__(self, *args):
self.x = args[0]
log.debug("FILE OPEN: %s" % str(self.x))
oldfile.__init__(self, *args)
openfiles.add(self)
def close(self):
log.debug("FILE CLOSED: %s" % str(self.x))
oldfile.close(self)
openfiles.remove(self)
def _open(*args):
return newfile(*args)
def monkeypatch_files():
"""Wraps builtin file operations to allow us to track open files"""
__builtin__.file = _file
__builtin__.open = _open
patched = True
def get_open_fd_count():
if 'Darwin' in platform.platform():
pid = os.getpid()
procs = subprocess.check_output([ "lsof", '-w', '-Ff', "-p", str(pid)])
nprocs = len(filter(lambda s: s and s[0] == 'f' and s[1:].isdigit(),procs.split('\n')))
return nprocs
# check if we've monkeypatched anything
if patched:
return len(get_open_files())
else:
# Will only work for Linux
return len(os.listdir('/proc/self/fd'))
def get_open_files():
return [f.x for f in openfiles]
def stats(pid):
"""Retrieve process kernel counters"""
stats = open('/proc/%d/status' % pid,'r').readlines()
return dict(filter(lambda x: len(x)==2,map(lambda x: x.split()[:2],stats)))
def rss(pid):
"""Retrieve a process' resident set size"""
try:
return int(stats(pid)['VmRSS:'])
except:
return 0