|
| 1 | +# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +"""Utilities for measuring cpu utilisation for a process.""" |
| 4 | +import time |
| 5 | + |
| 6 | +from subprocess import run, CalledProcessError, PIPE |
| 7 | +from threading import Thread |
| 8 | + |
| 9 | +# /proc/<pid>/stat output taken from |
| 10 | +# https://www.man7.org/linux/man-pages/man5/proc.5.html |
| 11 | +STAT_UTIME_IDX = 13 |
| 12 | +STAT_STIME_IDX = 14 |
| 13 | +STAT_STARTTIME_IDX = 21 |
| 14 | + |
| 15 | + |
| 16 | +class CpuLoadExceededException(Exception): |
| 17 | + """A custom exception containing details on excessive cpu load.""" |
| 18 | + |
| 19 | + def __init__(self, cpu_load_samples, threshold): |
| 20 | + """Compose the error message containing the cpu load details.""" |
| 21 | + super(CpuLoadExceededException, self).__init__( |
| 22 | + 'Cpu load samples {} exceeded maximum threshold {}.\n' |
| 23 | + .format(cpu_load_samples, threshold) |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +class CpuLoadMonitor(Thread): |
| 28 | + """Class to represent a cpu load monitor for a thread.""" |
| 29 | + |
| 30 | + CPU_LOAD_SAMPLES_TIMEOUT_S = 1 |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + process_pid, |
| 35 | + thread_pid, |
| 36 | + threshold |
| 37 | + ): |
| 38 | + """Set up monitor attributes.""" |
| 39 | + Thread.__init__(self) |
| 40 | + self._process_pid = process_pid |
| 41 | + self._thread_pid = thread_pid |
| 42 | + self._cpu_load_samples = [] |
| 43 | + self._threshold = threshold |
| 44 | + self._should_stop = False |
| 45 | + |
| 46 | + @property |
| 47 | + def process_pid(self): |
| 48 | + """Get the process pid.""" |
| 49 | + return self._process_pid |
| 50 | + |
| 51 | + @property |
| 52 | + def thread_pid(self): |
| 53 | + """Get the thread pid.""" |
| 54 | + return self._thread_pid |
| 55 | + |
| 56 | + @property |
| 57 | + def threshold(self): |
| 58 | + """Get the cpu load threshold.""" |
| 59 | + return self._threshold |
| 60 | + |
| 61 | + @property |
| 62 | + def cpu_load_samples(self): |
| 63 | + """Get the cpu load samples.""" |
| 64 | + return self._cpu_load_samples |
| 65 | + |
| 66 | + def signal_stop(self): |
| 67 | + """Signal that the thread should stop.""" |
| 68 | + self._should_stop = True |
| 69 | + |
| 70 | + def run(self): |
| 71 | + """Thread for monitoring cpu load of some pid. |
| 72 | +
|
| 73 | + `/proc/<process pid>/task/<thread pid>/stat` is used to compute |
| 74 | + the cpu load, which is then added to the list. |
| 75 | + It is up to the caller to check the queue. |
| 76 | + """ |
| 77 | + clock_ticks_cmd = 'getconf CLK_TCK' |
| 78 | + try: |
| 79 | + stdout = run( |
| 80 | + clock_ticks_cmd, |
| 81 | + shell=True, |
| 82 | + check=True, |
| 83 | + stdout=PIPE |
| 84 | + ).stdout.decode('utf-8') |
| 85 | + except CalledProcessError: |
| 86 | + return |
| 87 | + try: |
| 88 | + clock_ticks = int(stdout.strip("\n")) |
| 89 | + except ValueError: |
| 90 | + return |
| 91 | + |
| 92 | + while not self._should_stop: |
| 93 | + try: |
| 94 | + with open('/proc/uptime') as uptime_file: |
| 95 | + uptime = uptime_file.readline().strip("\n").split()[0] |
| 96 | + |
| 97 | + with open('/proc/{pid}/task/{tid}/stat'.format( |
| 98 | + pid=self.process_pid, |
| 99 | + tid=self.thread_pid) |
| 100 | + ) as stat_file: |
| 101 | + stat = stat_file.readline().strip("\n").split() |
| 102 | + except IOError: |
| 103 | + break |
| 104 | + |
| 105 | + try: |
| 106 | + uptime = float(uptime) |
| 107 | + utime = int(stat[STAT_UTIME_IDX]) |
| 108 | + stime = int(stat[STAT_STIME_IDX]) |
| 109 | + starttime = int(stat[STAT_STARTTIME_IDX]) |
| 110 | + except ValueError: |
| 111 | + break |
| 112 | + |
| 113 | + total_time = utime + stime |
| 114 | + seconds = uptime - starttime / clock_ticks |
| 115 | + cpu_load = (total_time * 100 / clock_ticks) / seconds |
| 116 | + |
| 117 | + if cpu_load > self.threshold: |
| 118 | + self.cpu_load_samples.append(cpu_load) |
| 119 | + |
| 120 | + time.sleep(self.CPU_LOAD_SAMPLES_TIMEOUT_S) |
| 121 | + |
| 122 | + def check_samples(self): |
| 123 | + """Check that there are no samples above the threshold.""" |
| 124 | + if len(self.cpu_load_samples) > 0: |
| 125 | + raise CpuLoadExceededException( |
| 126 | + self._cpu_load_samples, self._threshold) |
0 commit comments