blob: 2169cc2dce8d4f95bb5d84f6c75b1f70a20e9d80 [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
6import subprocess
7
8import psutil
9
10
Ian Wienand9573edb2017-03-28 19:37:39 +110011SUMMARY_REGEX = re.compile(b".*\s+(?P<locked>[\d]+)\s+KB")
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():
25 pid = proc.pid
26 # sadly psutil does not expose locked pages info, that's why we
27 # call to pmap and parse the output here
28 try:
29 out = subprocess.check_output(['pmap', '-XX', str(pid)])
30 except subprocess.CalledProcessError as e:
31 # 42 means process just vanished, which is ok
32 if e.returncode == 42:
33 continue
34 raise
35 last_line = out.splitlines()[-1]
36
37 # some processes don't provide a memory map, for example those
38 # running as kernel services, so we need to skip those that don't
39 # match
40 result = SUMMARY_REGEX.match(last_line)
41 if result:
42 locked = int(result.group('locked'))
43 if locked:
44 mlock_users.append({'name': proc.name(),
45 'pid': pid,
46 'locked': locked})
47
48 # produce a single line log message with per process mlock stats
49 if mlock_users:
50 return "; ".join(
51 "[%(name)s (pid:%(pid)s)]=%(locked)dKB" % args
52 # log heavy users first
53 for args in sorted(mlock_users, key=lambda d: d['locked'])
54 )
55 else:
56 return "no locked memory"
57
58
59if __name__ == "__main__":
60 main()