| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
"""Helper functions module with common useful functions""" |
| 19 |
|
| 20 |
from __future__ import annotations |
| 21 |
|
| 22 |
import contextlib |
| 23 |
import csv |
| 24 |
import json |
| 25 |
import logging |
| 26 |
import os |
| 27 |
import platform |
| 28 |
import re |
| 29 |
import signal |
| 30 |
import subprocess |
| 31 |
import sys |
| 32 |
import time |
| 33 |
from typing import IO, TYPE_CHECKING, Any, Literal, overload |
| 34 |
|
| 35 |
if TYPE_CHECKING: |
| 36 |
import psutil |
| 37 |
|
| 38 |
from collections import OrderedDict |
| 39 |
|
| 40 |
__version__ = "1.4.0" |
| 41 |
|
| 42 |
_DEFAULT = object() |
| 43 |
POSIX = os.name == "posix" |
| 44 |
ENCODING = sys.getfilesystemencoding() |
| 45 |
try: |
| 46 |
ENCODING_ERRS = sys.getfilesystemencodeerrors() |
| 47 |
except AttributeError: |
| 48 |
ENCODING_ERRS = "surrogateescape" if POSIX else "replace" |
| 49 |
|
| 50 |
|
| 51 |
def get_processor_name() -> str: |
| 52 |
"""Returns the processor name in the system""" |
| 53 |
if platform.system() == "Linux": |
| 54 |
with open("/proc/cpuinfo") as cpuinfo: |
| 55 |
for line in cpuinfo: |
| 56 |
if "model name" in line: |
| 57 |
return re.sub(r".*model name.*:", "", line, count=1) |
| 58 |
elif platform.system() == "FreeBSD": |
| 59 |
return subprocess.check_output(["sysctl", "-n", "hw.model"], text=True).strip() |
| 60 |
elif platform.system() == "Darwin": |
| 61 |
return subprocess.check_output( |
| 62 |
["sysctl", "-n", "machdep.cpu.brand_string"], text=True |
| 63 |
).strip() |
| 64 |
|
| 65 |
return platform.processor() |
| 66 |
|
| 67 |
|
| 68 |
def kill_child_processes(parent_proc: psutil.Process | None, timeout: int = 3) -> None: |
| 69 |
"""Kills a process and all its children gracefully. |
| 70 |
|
| 71 |
Attempts SIGTERM via process group first, falls back to per-process |
| 72 |
terminate, then SIGKILL after timeout. |
| 73 |
""" |
| 74 |
import psutil |
| 75 |
|
| 76 |
if parent_proc is None: |
| 77 |
logging.debug("No stress process to kill") |
| 78 |
return |
| 79 |
|
| 80 |
logging.debug("Killing stress process %s", parent_proc) |
| 81 |
|
| 82 |
|
| 83 |
try: |
| 84 |
pgid = os.getpgid(parent_proc.pid) |
| 85 |
os.killpg(pgid, signal.SIGTERM) |
| 86 |
logging.debug("Sent SIGTERM to process group %s", pgid) |
| 87 |
except (OSError, ProcessLookupError, AttributeError): |
| 88 |
te |
| 89 |
logging.debug("Process group kill failed, falling back to per-process") |
| 90 |
try: |
| 91 |
for proc in parent_proc.children(recursive=True): |
| 92 |
with contextlib.suppress(psutil.NoSuchProcess, ProcessLookupError): |
| 93 |
proc.terminate() |
| 94 |
parent_proc.terminate() |
| 95 |
except (psutil.NoSuchProcess, AttributeError): |
| 96 |
logging.debug("Process already gone during terminate") |
| 97 |
return |
| 98 |
|
| 99 |
|
| 100 |
try: |
| 101 |
_, alive = psutil.wait_procs( |
| 102 |
[parent_proc, *parent_proc.children(recursive=True)], |
| 103 |
timeout=timeout, |
| 104 |
) |
| 105 |
for proc in alive: |
| 106 |
logging.debug("Sending SIGKILL to straggler %s", proc) |
| 107 |
with contextlib.suppress(psutil.NoSuchProcess, ProcessLookupError): |
| 108 |
proc.kill() |
| 109 |
except (psutil.NoSuchProcess, AttributeError): |
| 110 |
logging.debug("Process already gone during wait") |
| 111 |
|
| 112 |
|
| 113 |
def _get_throttle_label(sources: Any) -> str: |
| 114 |
"""Return the aggregate throttle label from the first source that has one.""" |
| 115 |
for source in sources: |
| 116 |
if not source.get_is_available(): |
| 117 |
continue |
| 118 |
suffixes = source.get_sensor_suffixes() |
| 119 |
for s in suffixes: |
| 120 |
if s: |
| 121 |
return s |
| 122 |
return "" |
| 123 |
|
| 124 |
|
| 125 |
def output_to_csv(sources: dict, csv_writeable_file: str) -> None: |
| 126 |
"""Print statistics to csv file""" |
| 127 |
file_exists = os.path.isfile(csv_writeable_file) |
| 128 |
|
| 129 |
with open(csv_writeable_file, "a") as csvfile: |
| 130 |
csv_dict = OrderedDict() |
| 131 |
csv_dict.update({"Time": time.strftime("%Y-%m-%d_%H:%M:%S")}) |
| 132 |
summaries = [val for key, val in sources.items()] |
| 133 |
for summarie in summaries: |
| 134 |
source = summarie.source |
| 135 |
prefix = source.get_source_name() + ":" |
| 136 |
for prob, val in source.get_sensors_summary().items(): |
| 137 |
csv_dict[prefix + prob] = val |
| 138 |
|
| 139 |
csv_dict["Throttle"] = _get_throttle_label([s.source for s in summaries]) |
| 140 |
|
| 141 |
fieldnames = list(csv_dict.keys()) |
| 142 |
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) |
| 143 |
|
| 144 |
if not file_exists: |
| 145 |
writer.writeheader() |
| 146 |
writer.writerow(csv_dict) |
| 147 |
|
| 148 |
|
| 149 |
def output_to_terminal(sources: list) -> None: |
| 150 |
"""Print statistics to the terminal""" |
| 151 |
results = OrderedDict() |
| 152 |
for source in sources: |
| 153 |
if source.get_is_available(): |
| 154 |
source.update() |
| 155 |
source_name = source.get_source_name() |
| 156 |
results[source_name] = source.get_sensors_summary() |
| 157 |
throttle = _get_throttle_label(sources) |
| 158 |
if throttle: |
| 159 |
results["Throttle"] = {"reason": throttle} |
| 160 |
for key, value in results.items(): |
| 161 |
sys.stdout.write(str(key) + ": ") |
| 162 |
for skey, svalue in value.items(): |
| 163 |
sys.stdout.write(str(skey) + ": " + str(svalue) + ", ") |
| 164 |
sys.stdout.write("\n") |
| 165 |
sys.exit() |
| 166 |
|
| 167 |
|
| 168 |
def output_to_json(sources: list) -> None: |
| 169 |
"""Print statistics to the terminal in Json format""" |
| 170 |
results = OrderedDict() |
| 171 |
for source in sources: |
| 172 |
if source.get_is_available(): |
| 173 |
source.update() |
| 174 |
source_name = source.get_source_name() |
| 175 |
results[source_name] = source.get_sensors_summary() |
| 176 |
throttle = _get_throttle_label(sources) |
| 177 |
results["Throttle"] = throttle |
| 178 |
print(json.dumps(results, indent=4)) |
| 179 |
sys.exit() |
| 180 |
|
| 181 |
|
| 182 |
def _get_xdg_config_home() -> str: |
| 183 |
"""Return the XDG config home directory, with fallback to ~/.config""" |
| 184 |
user_home = os.getenv("XDG_CONFIG_HOME") |
| 185 |
if user_home: |
| 186 |
return user_home |
| 187 |
return os.path.expanduser(os.path.join("~", ".config")) |
| 188 |
|
| 189 |
|
| 190 |
def get_config_dir() -> str: |
| 191 |
""" |
| 192 |
Return the path to the user home config directory |
| 193 |
""" |
| 194 |
return _get_xdg_config_home() |
| 195 |
|
| 196 |
|
| 197 |
def get_user_config_dir() -> str: |
| 198 |
""" |
| 199 |
Return the path to the user s-tui config directory |
| 200 |
""" |
| 201 |
return os.path.join(_get_xdg_config_home(), "s-tui") |
| 202 |
|
| 203 |
|
| 204 |
def get_user_config_file() -> str: |
| 205 |
""" |
| 206 |
Return the path to the user s-tui config file |
| 207 |
""" |
| 208 |
return os.path.join(get_user_config_dir(), "s-tui.conf") |
| 209 |
|
| 210 |
|
| 211 |
def user_config_dir_exists() -> bool: |
| 212 |
""" |
| 213 |
Check whether the user s-tui config dir exists or not |
| 214 |
""" |
| 215 |
return os.path.isdir(get_user_config_dir()) |
| 216 |
|
| 217 |
|
| 218 |
def config_dir_exists() -> bool: |
| 219 |
""" |
| 220 |
Check whether the home config dir exists or not |
| 221 |
""" |
| 222 |
return os.path.isdir(get_config_dir()) |
| 223 |
|
| 224 |
|
| 225 |
def user_config_file_exists() -> bool: |
| 226 |
""" |
| 227 |
Check whether the user s-tui config file exists or not |
| 228 |
""" |
| 229 |
return os.path.isfile(get_user_config_file()) |
| 230 |
|
| 231 |
|
| 232 |
def make_user_config_dir() -> str | None: |
| 233 |
""" |
| 234 |
Create the user s-tui config directory if it doesn't exist |
| 235 |
""" |
| 236 |
config_dir = get_config_dir() |
| 237 |
config_path = get_user_config_dir() |
| 238 |
|
| 239 |
if not config_dir_exists(): |
| 240 |
try: |
| 241 |
os.mkdir(config_dir) |
| 242 |
except OSError: |
| 243 |
return None |
| 244 |
|
| 245 |
if not user_config_dir_exists(): |
| 246 |
try: |
| 247 |
os.mkdir(config_path) |
| 248 |
os.mkdir(os.path.join(config_path, "hooks.d")) |
| 249 |
except OSError: |
| 250 |
return None |
| 251 |
|
| 252 |
return config_path |
| 253 |
|
| 254 |
|
| 255 |
def seconds_to_text(secs: float) -> str: |
| 256 |
"""Converts seconds to a string of hours:minutes:seconds""" |
| 257 |
hours = (secs) // 3600 |
| 258 |
minutes = (secs - hours * 3600) // 60 |
| 259 |
seconds = secs - hours * 3600 - minutes * 60 |
| 260 |
return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}" |
| 261 |
|
| 262 |
|
| 263 |
def str_to_bool(string: str) -> bool: |
| 264 |
"""Converts a string to a boolean""" |
| 265 |
if string == "True": |
| 266 |
return True |
| 267 |
if string == "False": |
| 268 |
return False |
| 269 |
raise ValueError |
| 270 |
|
| 271 |
|
| 272 |
def which(program: str) -> str | None: |
| 273 |
"""Find the path of an executable""" |
| 274 |
|
| 275 |
def is_exe(fpath): |
| 276 |
return os.path.isfile(fpath) and os.access(fpath, os.X_OK) |
| 277 |
|
| 278 |
fpath, _ = os.path.split(program) |
| 279 |
if fpath: |
| 280 |
if is_exe(program): |
| 281 |
return program |
| 282 |
else: |
| 283 |
for path in os.environ["PATH"].split(os.pathsep): |
| 284 |
exe_file = os.path.join(path, program) |
| 285 |
if is_exe(exe_file): |
| 286 |
return exe_file |
| 287 |
|
| 288 |
return None |
| 289 |
|
| 290 |
|
| 291 |
def _open_binary(fname: str, **kwargs: Any) -> IO[bytes]: |
| 292 |
return open(fname, "rb", **kwargs) |
| 293 |
|
| 294 |
|
| 295 |
def _open_text(fname: str, **kwargs: Any) -> IO[str]: |
| 296 |
"""Opens a file in text mode by using fs encoding and |
| 297 |
a proper en/decoding errors handler. |
| 298 |
""" |
| 299 |
kwargs.setdefault("encoding", ENCODING) |
| 300 |
kwargs.setdefault("errors", ENCODING_ERRS) |
| 301 |
return open(fname, **kwargs) |
| 302 |
|
| 303 |
|
| 304 |
@overload |
| 305 |
def cat(fname: str, fallback: object = ..., *, binary: Literal[True]) -> bytes: ... |
| 306 |
|
| 307 |
|
| 308 |
@overload |
| 309 |
def cat(fname: str, fallback: object = ..., *, binary: Literal[False]) -> str: ... |
| 310 |
|
| 311 |
|
| 312 |
@overload |
| 313 |
def cat(fname: str, fallback: object = ..., binary: bool = ...) -> bytes | str: ... |
| 314 |
|
| 315 |
|
| 316 |
def cat(fname, fallback=_DEFAULT, binary=True): |
| 317 |
"""Return file content. |
| 318 |
fallback: the value returned in case the file does not exist or |
| 319 |
cannot be read |
| 320 |
binary: whether to open the file in binary or text mode. |
| 321 |
""" |
| 322 |
try: |
| 323 |
with _open_binary(fname) if binary else _open_text(fname) as f_d: |
| 324 |
return f_d.read().strip() |
| 325 |
except OSError: |
| 326 |
if fallback is not _DEFAULT: |
| 327 |
return fallback |
| 328 |
raise |