blob: b15a0bf80be4dc84db2ef9ac60fc92d6b41efc81 [file] [log] [blame]
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +00001# This tool lists processes that lock memory pages from swapping to disk.
2
3import re
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +00004
5import psutil
6
7
Dirk Mueller02f9e8b2017-09-10 02:51:10 +02008LCK_SUMMARY_REGEX = re.compile(
9 "^VmLck:\s+(?P<locked>[\d]+)\s+kB", re.MULTILINE)
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +000010
11
12def main():
13 try:
Ian Wienand9573edb2017-03-28 19:37:39 +110014 print(_get_report())
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +000015 except Exception as e:
Ian Wienand9573edb2017-03-28 19:37:39 +110016 print("Failure listing processes locking memory: %s" % str(e))
17 raise
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +000018
19
20def _get_report():
21 mlock_users = []
22 for proc in psutil.process_iter():
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +000023 # sadly psutil does not expose locked pages info, that's why we
Dirk Mueller02f9e8b2017-09-10 02:51:10 +020024 # iterate over the /proc/%pid/status files manually
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +000025 try:
Dirk Mueller02f9e8b2017-09-10 02:51:10 +020026 s = open("%s/%d/status" % (psutil.PROCFS_PATH, proc.pid), 'r')
27 except EnvironmentError:
28 continue
29 with s:
30 for line in s:
31 result = LCK_SUMMARY_REGEX.search(line)
32 if result:
33 locked = int(result.group('locked'))
34 if locked:
35 mlock_users.append({'name': proc.name(),
36 'pid': proc.pid,
37 'locked': locked})
Ihar Hrachyshka2b4735f2017-02-10 06:17:37 +000038
39 # produce a single line log message with per process mlock stats
40 if mlock_users:
41 return "; ".join(
42 "[%(name)s (pid:%(pid)s)]=%(locked)dKB" % args
43 # log heavy users first
44 for args in sorted(mlock_users, key=lambda d: d['locked'])
45 )
46 else:
47 return "no locked memory"
48
49
50if __name__ == "__main__":
51 main()