Ihar Hrachyshka | 2b4735f | 2017-02-10 06:17:37 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | # This tool lists processes that lock memory pages from swapping to disk. |
| 4 | |
| 5 | import re |
| 6 | import subprocess |
| 7 | |
| 8 | import psutil |
| 9 | |
| 10 | |
Ian Wienand | 9573edb | 2017-03-28 19:37:39 +1100 | [diff] [blame] | 11 | SUMMARY_REGEX = re.compile(b".*\s+(?P<locked>[\d]+)\s+KB") |
Ihar Hrachyshka | 2b4735f | 2017-02-10 06:17:37 +0000 | [diff] [blame] | 12 | |
| 13 | |
| 14 | def main(): |
| 15 | try: |
Ian Wienand | 9573edb | 2017-03-28 19:37:39 +1100 | [diff] [blame] | 16 | print(_get_report()) |
Ihar Hrachyshka | 2b4735f | 2017-02-10 06:17:37 +0000 | [diff] [blame] | 17 | except Exception as e: |
Ian Wienand | 9573edb | 2017-03-28 19:37:39 +1100 | [diff] [blame] | 18 | print("Failure listing processes locking memory: %s" % str(e)) |
| 19 | raise |
Ihar Hrachyshka | 2b4735f | 2017-02-10 06:17:37 +0000 | [diff] [blame] | 20 | |
| 21 | |
| 22 | def _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 | |
| 59 | if __name__ == "__main__": |
| 60 | main() |