Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/firecracker
Path: blob/main/tests/host_tools/cpu_load.py
1956 views
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
from threading import Thread
6
import framework.utils as utils
7
8
# /proc/<pid>/stat output taken from
9
# https://www.man7.org/linux/man-pages/man5/proc.5.html
10
STAT_UTIME_IDX = 13
11
STAT_STIME_IDX = 14
12
STAT_STARTTIME_IDX = 21
13
14
15
class CpuLoadExceededException(Exception):
16
"""A custom exception containing details on excessive cpu load."""
17
18
def __init__(self, cpu_load_samples, threshold):
19
"""Compose the error message containing the cpu load details."""
20
super().__init__(
21
'Cpu load samples {} exceeded maximum threshold {}.\n'
22
.format(cpu_load_samples, threshold)
23
)
24
25
26
class CpuLoadMonitor(Thread):
27
"""Class to represent a cpu load monitor for a thread."""
28
29
CPU_LOAD_SAMPLES_TIMEOUT_S = 1
30
31
def __init__(
32
self,
33
process_pid,
34
thread_pid,
35
threshold
36
):
37
"""Set up monitor attributes."""
38
Thread.__init__(self)
39
self._process_pid = process_pid
40
self._thread_pid = thread_pid
41
self._cpu_load_samples = []
42
self._threshold = threshold
43
self._should_stop = False
44
45
@property
46
def process_pid(self):
47
"""Get the process pid."""
48
return self._process_pid
49
50
@property
51
def thread_pid(self):
52
"""Get the thread pid."""
53
return self._thread_pid
54
55
@property
56
def threshold(self):
57
"""Get the cpu load threshold."""
58
return self._threshold
59
60
@property
61
def cpu_load_samples(self):
62
"""Get the cpu load samples."""
63
return self._cpu_load_samples
64
65
def signal_stop(self):
66
"""Signal that the thread should stop."""
67
self._should_stop = True
68
69
def run(self):
70
"""Thread for monitoring cpu load of some pid.
71
72
It is up to the caller to check the queue.
73
"""
74
while not self._should_stop:
75
cpu_load = utils.ProcessManager.get_cpu_percent(
76
self._process_pid)["real"]
77
if cpu_load > self.threshold:
78
self.cpu_load_samples.append(cpu_load)
79
time.sleep(1) # 1 second granularity.
80
81
def check_samples(self):
82
"""Check that there are no samples above the threshold."""
83
if len(self.cpu_load_samples) > 0:
84
raise CpuLoadExceededException(
85
self._cpu_load_samples, self._threshold)
86
87