acceptancetest_high_cpu.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # Copyright (c) 2020 Pilz GmbH & Co. KG
3 
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Lesser General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Lesser General Public License for more details.
13 
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this program. If not, see <https://www.gnu.org/licenses/>.
16 
17 import time
18 import sys
19 import psutil
20 
21 OBSERVATION_FREQUENCY_HZ = .5
22 OBSERVATION_DURATION_SEC = 60
23 PSEN_SCAN_PROCESS_NAME = "psen_scan_node"
24 NAME = 'name'
25 THRESHOLD_PRECENT = 80
26 RETURN_CODE_SUCCESS = 0
27 RETURN_CODE_FAILURE = 10
28 RETURN_CODE_ERROR = 1
29 
30 # ASCII codes for printing colored text to console
31 GREEN = '\033[92m'
32 YELLOW = '\033[93m'
33 RED = '\033[91m'
34 NC = '\033[0m'
35 
36 
37 def get_psen_scan_process(): # type: () -> psutil.Process
38  """Return the handle of the psen_scan process if it is currently running,
39  None otherwise."""
40  for proc in psutil.process_iter([NAME]):
41  if proc.info[NAME] == PSEN_SCAN_PROCESS_NAME:
42  return proc
43  raise RuntimeError("Process %s not found." % PSEN_SCAN_PROCESS_NAME)
44 
45 
46 if __name__ == "__main__":
47  process = None
48  while process is None:
49  try:
50  process = get_psen_scan_process()
51  except RuntimeError:
52  print("Waiting for %s process to be running." %
53  PSEN_SCAN_PROCESS_NAME)
54  time.sleep(1. / OBSERVATION_FREQUENCY_HZ)
55  print(YELLOW +
56  "Process is running. Will observe its CPU usage now for %d seconds" %
57  OBSERVATION_DURATION_SEC + NC)
58  start_time = time.time()
59  while time.time() - start_time < OBSERVATION_DURATION_SEC:
60  try:
61  process = get_psen_scan_process()
62  except RuntimeError:
63  print(RED + "Process not running any more. Aborting Test" + NC)
64  sys.exit(RETURN_CODE_FAILURE)
65  utilization = process.cpu_percent()
66  if utilization < THRESHOLD_PRECENT:
67  print("CPU utilization of >%s<: %.1f%%" %
68  (PSEN_SCAN_PROCESS_NAME, utilization))
69  else:
70  print(RED +
71  "CPU utilization of >%s<: %.1f%% " %
72  (PSEN_SCAN_PROCESS_NAME, utilization) +
73  "exceeds threshold of %d%%" %
74  THRESHOLD_PRECENT + NC)
75  sys.exit(RETURN_CODE_ERROR)
76  time.sleep(1. / OBSERVATION_FREQUENCY_HZ)
77  print(GREEN + "CPU usage was below %d%% for %d seconds. " %
78  (THRESHOLD_PRECENT, OBSERVATION_DURATION_SEC) +
79  "Test successful." + NC)
80  sys.exit(RETURN_CODE_SUCCESS)


psen_scan
Author(s):
autogenerated on Mon Feb 28 2022 23:16:20