Coretex
statistics.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Tuple
19 
20 import os
21 import logging
22 import shutil
23 
24 from py3nvml import py3nvml
25 
26 import psutil
27 
28 
29 def getCpuUsage() -> float:
30  """
31  Returns
32  -------
33  float -> CPU usage as percentage since last call of this function
34  """
35 
36  return psutil.cpu_percent()
37 
38 
39 def getRamUsage() -> float:
40  """
41  Returns
42  -------
43  float -> Used RAM memory as percentage
44  """
45 
46  return psutil.virtual_memory().percent
47 
48 
49 def getAvailableRam() -> int:
50  """
51  Returns
52  -------
53  int -> total RAM memory in GB as int
54  """
55 
56  memory = psutil.virtual_memory()
57  return int(memory.total / (1024 ** 3))
58 
59 
60 def getAvailableCpuCount() -> int:
61  availableCPUs = os.cpu_count()
62  return availableCPUs if availableCPUs is not None else 1
63 
64 
65 def getGpuUsage() -> float:
66  """
67  py3nvml init must be called before calling this function
68  otherwise it will raise an exception
69 
70  Returns
71  -------
72  float -> GPU usage as percentage
73  """
74 
75  handle = py3nvml.nvmlDeviceGetHandleByIndex(0)
76  utilization = py3nvml.nvmlDeviceGetUtilizationRates(handle)
77 
78  if isinstance(utilization, py3nvml.c_nvmlUtilization_t):
79  return float(utilization.gpu)
80 
81  logging.getLogger("coretexpylib").debug(">> [Coretex] Failed to extract gpu usage metric")
82  return 0
83 
84 
85 def getGpuMemoryUsage() -> float:
86  """
87  py3nvml init must be called before calling this function
88  otherwise it will raise an exception
89 
90  Returns
91  -------
92  float -> GPU memory usage as percentage
93  """
94 
95  handle = py3nvml.nvmlDeviceGetHandleByIndex(0)
96  memory = py3nvml.nvmlDeviceGetMemoryInfo(handle)
97 
98  if not isinstance(memory, py3nvml.c_nvmlMemory_t):
99  logging.getLogger("coretexpylib").debug(">> [Coretex] Failed to extract gpu memory usage metric")
100  return 0
101 
102  return float(memory.used / memory.total * 100)
103 
104 
105 def getGpuTemperature() -> float:
106  """
107  py3nvml init must be called before calling this function
108  otherwise it will raise an exception
109 
110  Returns
111  -------
112  float -> GPU temperature
113  """
114 
115  handle = py3nvml.nvmlDeviceGetHandleByIndex(0)
116  temperature = py3nvml.nvmlDeviceGetTemperature(handle, py3nvml.NVML_TEMPERATURE_GPU)
117 
118  return float(temperature)
119 
120 
121 def getSwapUsage() -> float:
122  """
123  Returns
124  -------
125  float -> Used swap memory as percentage
126  """
127 
128  return psutil.swap_memory().percent
129 
130 
131 def getTotalSwapMemory() -> int:
132  """
133  Returns
134  -------
135  int -> total swap memory in GB
136  """
137 
138  return int(psutil.swap_memory().total / (1024 ** 3))
139 
140 
141 def getDiskRead() -> float:
142  """
143  Returns
144  -------
145  float -> total amount of bytes read from disk
146  """
147 
148  counters = psutil.disk_io_counters()
149 
150  if counters is None:
151  logging.getLogger("coretexpylib").debug(">> [Coretex] Failed to extract disk read metric")
152  return 0
153 
154  return float(counters.read_bytes)
155 
156 
157 def getDiskWrite() -> float:
158  """
159  Returns
160  -------
161  float -> total amount of bytes wrote to disk
162  """
163 
164  counters = psutil.disk_io_counters()
165 
166  if counters is None:
167  logging.getLogger("coretexpylib").debug(">> [Coretex] Failed to extract disk write metric")
168  return 0
169 
170  return float(counters.write_bytes)
171 
172 
173 def getStorageUsage() -> float:
174  """
175  Returns
176  -------
177  float -> Used storage space as percentage
178  """
179 
180  info = shutil.disk_usage("/")
181  return info.used / info.total * 100 # 0-1 range -> 0-100 range
182 
183 
184 def _getNetworkUsage() -> Tuple[float, float]:
185  counters = psutil.net_io_counters(pernic = True)
186 
187  totalBytesRecv = 0
188  totalBytesSent = 0
189 
190  for counter in counters.values():
191  bytesRecv = counter.bytes_recv
192  bytesSent = counter.bytes_sent
193 
194  totalBytesRecv += bytesRecv
195  totalBytesSent += bytesSent
196 
197  return float(totalBytesRecv * 8), float(totalBytesSent * 8)
198 
199 
200 def getDownloadSpeed() -> float:
201  """
202  Returns
203  -------
204  float -> total amount of bytes downloaded
205  """
206 
207  return _getNetworkUsage()[0]
208 
209 
210 def getUploadSpeed() -> float:
211  """
212  Returns
213  -------
214  float -> total amount of bytes uploaded
215  """
216 
217  return _getNetworkUsage()[1]