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