blob: 1b081bbe6f8b5634dd1601b09e6f47e1820de78e [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')
Ian Wienandb02a4322018-11-27 12:59:04 +110027 with s:
28 for line in s:
29 result = LCK_SUMMARY_REGEX.search(line)
30 if result:
31 locked = int(result.group('locked'))
32 if locked:
33 mlock_users.append({'name': proc.name(),
34 'pid': proc.pid,
35 'locked': locked})
36 except OSError:
37 # pids can disappear, we're ok with that
Dirk Mueller02f9e8b2017-09-10 02:51:10 +020038 continue
Ian Wienandb02a4322018-11-27 12:59:04 +110039
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()