| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
"""CPU stress and monitoring utility""" |
| 22 |
|
| 23 |
import argparse |
| 24 |
import atexit |
| 25 |
import configparser |
| 26 |
import contextlib |
| 27 |
import logging |
| 28 |
import os |
| 29 |
import signal |
| 30 |
import subprocess |
| 31 |
import sys |
| 32 |
import time |
| 33 |
import timeit |
| 34 |
from collections import OrderedDict, defaultdict |
| 35 |
|
| 36 |
import psutil |
| 37 |
import urwid |
| 38 |
|
| 39 |
|
| 40 |
from s_tui.about_menu import AboutMenu |
| 41 |
from s_tui.builtin_stress_menu import BuiltinStressMenu |
| 42 |
from s_tui.builtin_stresser import BuiltinStresser |
| 43 |
from s_tui.help_menu import HELP_MESSAGE, HelpMenu |
| 44 |
|
| 45 |
|
| 46 |
from s_tui.helper_functions import ( |
| 47 |
__version__, |
| 48 |
cat, |
| 49 |
get_processor_name, |
| 50 |
get_user_config_dir, |
| 51 |
get_user_config_file, |
| 52 |
kill_child_processes, |
| 53 |
make_user_config_dir, |
| 54 |
output_to_csv, |
| 55 |
output_to_json, |
| 56 |
output_to_terminal, |
| 57 |
seconds_to_text, |
| 58 |
str_to_bool, |
| 59 |
user_config_dir_exists, |
| 60 |
user_config_file_exists, |
| 61 |
which, |
| 62 |
) |
| 63 |
from s_tui.power_profile_menu import ( |
| 64 |
SYSFS_AVAIL_EPP, |
| 65 |
SYSFS_AVAIL_GOVERNORS, |
| 66 |
SYSFS_EPP, |
| 67 |
SYSFS_GOVERNOR, |
| 68 |
PowerProfileMenu, |
| 69 |
read_available, |
| 70 |
) |
| 71 |
from s_tui.sensors_menu import SensorsMenu |
| 72 |
from s_tui.sources.fan_source import FanSource |
| 73 |
from s_tui.sources.freq_source import FreqSource |
| 74 |
from s_tui.sources.rapl_power_source import RaplPowerSource |
| 75 |
from s_tui.sources.script_hook_loader import ScriptHookLoader |
| 76 |
from s_tui.sources.temp_source import TempSource |
| 77 |
|
| 78 |
|
| 79 |
from s_tui.sources.util_source import UtilSource |
| 80 |
from s_tui.stress_menu import StressMenu |
| 81 |
from s_tui.sturwid.bar_graph_vector import BarGraphVector |
| 82 |
from s_tui.sturwid.summary_text_list import SummaryTextList |
| 83 |
|
| 84 |
|
| 85 |
from s_tui.sturwid.ui_elements import DEFAULT_PALETTE, ViListBox, button, radio_button |
| 86 |
|
| 87 |
UPDATE_INTERVAL = 1 |
| 88 |
HOOK_INTERVAL = 30 * 1000 |
| 89 |
DEGREE_SIGN = "\N{DEGREE SIGN}" |
| 90 |
ZERO_TIME = seconds_to_text(0) |
| 91 |
|
| 92 |
DEFAULT_LOG_FILE = "_s-tui.log" |
| 93 |
|
| 94 |
DEFAULT_CSV_FILE = "s-tui_log_" + time.strftime("%Y-%m-%d_%H_%M_%S") + ".csv" |
| 95 |
|
| 96 |
VERSION_MESSAGE = ( |
| 97 |
"s-tui " |
| 98 |
+ __version__ |
| 99 |
+ " - (C) 2017-2025 Alex Manuskin, Gil Tsuker\n\ |
| 100 |
Released under GNU GPLv2" |
| 101 |
) |
| 102 |
|
| 103 |
ERROR_MESSAGE = "\n\ |
| 104 |
Oops! s-tui has encountered a fatal error\n\ |
| 105 |
Please report this bug here: https://github.com/amanusk/s-tui" |
| 106 |
|
| 107 |
graph_controller = None |
| 108 |
|
| 109 |
|
| 110 |
class MainLoop(urwid.MainLoop): |
| 111 |
"""Inherit urwid Mainloop to catch special character inputs""" |
| 112 |
|
| 113 |
def __init__(self, *args, **kwargs): |
| 114 |
super().__init__(*args, **kwargs) |
| 115 |
signal.signal(signal.SIGINT, self._signal_handler) |
| 116 |
signal.signal(signal.SIGTERM, self._signal_handler) |
| 117 |
|
| 118 |
def _signal_handler(self, signum: int, frame: object) -> None: |
| 119 |
"""signal handler for properly exiting Ctrl+C""" |
| 120 |
if graph_controller is not None: |
| 121 |
graph_controller.stress_controller.kill_stress_process() |
| 122 |
raise urwid.ExitMainLoop() |
| 123 |
|
| 124 |
def unhandled_input(self, data): |
| 125 |
logging.debug("Caught %s", data) |
| 126 |
if graph_controller is None: |
| 127 |
return |
| 128 |
if data == "q": |
| 129 |
graph_controller.stress_controller.kill_stress_process() |
| 130 |
raise urwid.ExitMainLoop() |
| 131 |
|
| 132 |
if data == "f1": |
| 133 |
graph_controller.view.on_help_menu_open(graph_controller.view.main_window_w) |
| 134 |
|
| 135 |
if data == "esc": |
| 136 |
graph_controller.view.on_menu_close() |
| 137 |
|
| 138 |
|
| 139 |
class StressController: |
| 140 |
""" |
| 141 |
Responsible for storing the data related to stress test options |
| 142 |
and operation |
| 143 |
""" |
| 144 |
|
| 145 |
def __init__(self, stress_installed): |
| 146 |
self.stress_modes = ["Monitor"] |
| 147 |
self.stress_modes.append("s-tui stress") |
| 148 |
|
| 149 |
if stress_installed: |
| 150 |
self.stress_modes.append("Stress (ext)") |
| 151 |
|
| 152 |
self.current_mode = self.stress_modes[0] |
| 153 |
self.stress_process = None |
| 154 |
self._builtin_stresser = None |
| 155 |
|
| 156 |
def get_modes(self): |
| 157 |
"""Returns all possible stress_modes for stress operations""" |
| 158 |
return self.stress_modes |
| 159 |
|
| 160 |
def get_current_mode(self): |
| 161 |
"""Returns the current stress test mode, monitor/stress/other""" |
| 162 |
return self.current_mode |
| 163 |
|
| 164 |
def set_mode(self, mode): |
| 165 |
"""Sets a stress test mode monitor/stress/other""" |
| 166 |
self.current_mode = mode |
| 167 |
|
| 168 |
def get_stress_process(self): |
| 169 |
"""Returns the current external stress process running""" |
| 170 |
return self.stress_process |
| 171 |
|
| 172 |
def set_stress_process(self, proc): |
| 173 |
"""Sets the current stress process running""" |
| 174 |
self.stress_process = proc |
| 175 |
|
| 176 |
@property |
| 177 |
def builtin_stresser(self): |
| 178 |
"""Lazy-init BuiltinStresser on first use. |
| 179 |
|
| 180 |
Avoids creating multiprocessing primitives at startup, which can |
| 181 |
fail in restricted environments (e.g. containers without |
| 182 |
/dev/shm). |
| 183 |
""" |
| 184 |
if self._builtin_stresser is None: |
| 185 |
self._builtin_stresser = BuiltinStresser() |
| 186 |
return self._builtin_stresser |
| 187 |
|
| 188 |
def kill_stress_process(self): |
| 189 |
"""Kills the current running stress process""" |
| 190 |
try: |
| 191 |
kill_child_processes(self.stress_process) |
| 192 |
except psutil.NoSuchProcess: |
| 193 |
logging.debug("Stress process no longer exists") |
| 194 |
self.stress_process = None |
| 195 |
if self._builtin_stresser is not None: |
| 196 |
self._builtin_stresser.stop() |
| 197 |
|
| 198 |
def start_stress(self, stress_cmd): |
| 199 |
"""Starts a new stress process with a given cmd""" |
| 200 |
with open(os.devnull, "w") as dev_null: |
| 201 |
try: |
| 202 |
stress_proc = subprocess.Popen( |
| 203 |
stress_cmd, |
| 204 |
stdout=dev_null, |
| 205 |
stderr=dev_null, |
| 206 |
start_new_session=True, |
| 207 |
) |
| 208 |
self.set_stress_process(psutil.Process(stress_proc.pid)) |
| 209 |
except OSError: |
| 210 |
logging.debug("Unable to start stress") |
| 211 |
|
| 212 |
def start_builtin_stress(self, num_workers, strategy=None): |
| 213 |
"""Starts the built-in Python CPU stresser.""" |
| 214 |
try: |
| 215 |
self.builtin_stresser.start(num_workers, strategy=strategy) |
| 216 |
except OSError as err: |
| 217 |
logging.error("Unable to start built-in stresser: %s", err) |
| 218 |
self.current_mode = "Monitor" |
| 219 |
|
| 220 |
|
| 221 |
class GraphView(urwid.WidgetPlaceholder): |
| 222 |
""" |
| 223 |
A class responsible for providing the application's interface and |
| 224 |
graph display. |
| 225 |
The GraphView can change the state of the graph, since it provides the UI |
| 226 |
The change is state should be reflected in the GraphController |
| 227 |
""" |
| 228 |
|
| 229 |
def __init__(self, controller): |
| 230 |
|
| 231 |
self.left_margin = 0 |
| 232 |
self.top_margin = 0 |
| 233 |
|
| 234 |
|
| 235 |
self.controller = controller |
| 236 |
self.main_window_w = [] |
| 237 |
|
| 238 |
|
| 239 |
self.source_update_errors = {} |
| 240 |
|
| 241 |
|
| 242 |
self.clock_view = urwid.Text(ZERO_TIME, align="center") |
| 243 |
self.governor_view = urwid.Text("", align="center") |
| 244 |
self.epp_view = urwid.Text("", align="center") |
| 245 |
self._update_cpu_policy() |
| 246 |
self.refresh_rate_ctrl = urwid.Edit( |
| 247 |
("Refresh[s]:"), self.controller.refresh_rate |
| 248 |
) |
| 249 |
self.hline = urwid.AttrMap(urwid.SolidFill(" "), "line") |
| 250 |
|
| 251 |
self.mode_buttons = [] |
| 252 |
|
| 253 |
self.summary_widget_index = None |
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
self.graph_place_holder = urwid.WidgetPlaceholder(urwid.Pile([])) |
| 258 |
|
| 259 |
|
| 260 |
self.stress_menu = StressMenu(self.on_menu_close, self.controller.stress_exe) |
| 261 |
self.builtin_stress_menu = BuiltinStressMenu(self.on_menu_close) |
| 262 |
self.help_menu = HelpMenu(self.on_menu_close) |
| 263 |
self.about_menu = AboutMenu(self.on_menu_close) |
| 264 |
self.graphs_menu = SensorsMenu( |
| 265 |
self.on_graphs_menu_close, |
| 266 |
self.controller.sources, |
| 267 |
self.controller.graphs_default_conf, |
| 268 |
) |
| 269 |
self.summary_menu = SensorsMenu( |
| 270 |
self.on_summary_menu_close, |
| 271 |
self.controller.sources, |
| 272 |
self.controller.summary_default_conf, |
| 273 |
) |
| 274 |
|
| 275 |
|
| 276 |
self.power_profile_menu = self._create_power_profile_menu() |
| 277 |
|
| 278 |
|
| 279 |
urwid.WidgetPlaceholder.__init__(self, self.main_window()) |
| 280 |
urwid.connect_signal(self.refresh_rate_ctrl, "change", self.update_refresh_rate) |
| 281 |
|
| 282 |
def update_refresh_rate(self, _, new_refresh_rate): |
| 283 |
|
| 284 |
if "q" in new_refresh_rate: |
| 285 |
self.on_exit_program() |
| 286 |
|
| 287 |
try: |
| 288 |
if float(new_refresh_rate) <= 0.001: |
| 289 |
pass |
| 290 |
else: |
| 291 |
self.controller.refresh_rate = new_refresh_rate |
| 292 |
except ValueError: |
| 293 |
self.controller.refresh_rate = "2.0" |
| 294 |
|
| 295 |
def update_displayed_information(self): |
| 296 |
"""Update all the graphs that are being displayed""" |
| 297 |
|
| 298 |
recoverable_source_errors = (OSError, IOError, TypeError, ValueError) |
| 299 |
debug_mode = self.controller.args.debug or self.controller.args.debug_run |
| 300 |
|
| 301 |
for source in self.controller.sources: |
| 302 |
source_name = source.get_source_name() |
| 303 |
if any(self.graphs_menu.active_sensors[source_name]) or any( |
| 304 |
self.summary_menu.active_sensors[source_name] |
| 305 |
): |
| 306 |
try: |
| 307 |
source.update() |
| 308 |
previous_error = self.source_update_errors.pop(source_name, None) |
| 309 |
if previous_error is not None: |
| 310 |
logging.info( |
| 311 |
"Source %s recovered from update errors (%s)", |
| 312 |
source_name, |
| 313 |
previous_error, |
| 314 |
) |
| 315 |
except recoverable_source_errors as err: |
| 316 |
error_name = err.__class__.__name__ |
| 317 |
previous_error = self.source_update_errors.get(source_name) |
| 318 |
self.source_update_errors[source_name] = error_name |
| 319 |
if previous_error != error_name: |
| 320 |
logging.warning( |
| 321 |
"Source %s update failed with recoverable %s: %s", |
| 322 |
source_name, |
| 323 |
error_name, |
| 324 |
err, |
| 325 |
) |
| 326 |
else: |
| 327 |
logging.debug( |
| 328 |
"Source %s update still failing with %s", |
| 329 |
source_name, |
| 330 |
error_name, |
| 331 |
) |
| 332 |
except Exception as err: |
| 333 |
error_name = err.__class__.__name__ |
| 334 |
self.source_update_errors[source_name] = error_name |
| 335 |
logging.exception( |
| 336 |
"Source %s update failed with unexpected %s", |
| 337 |
source_name, |
| 338 |
error_name, |
| 339 |
) |
| 340 |
if debug_mode: |
| 341 |
raise |
| 342 |
|
| 343 |
for graph in self.visible_graphs.values(): |
| 344 |
try: |
| 345 |
graph.update() |
| 346 |
except IndexError: |
| 347 |
logging.debug("Graph update failed") |
| 348 |
|
| 349 |
|
| 350 |
for summary in self.visible_summaries.values(): |
| 351 |
try: |
| 352 |
summary.update() |
| 353 |
except IndexError: |
| 354 |
logging.debug("Summary update failed") |
| 355 |
|
| 356 |
self._update_cpu_policy() |
| 357 |
|
| 358 |
|
| 359 |
if self.controller.stress_controller.get_current_mode() != "Monitor": |
| 360 |
self.clock_view.set_text( |
| 361 |
seconds_to_text( |
| 362 |
timeit.default_timer() - self.controller.stress_start_time |
| 363 |
) |
| 364 |
) |
| 365 |
|
| 366 |
def on_reset_button(self, _): |
| 367 |
"""Reset graph data and display empty graph""" |
| 368 |
for graph in self.visible_graphs.values(): |
| 369 |
graph.reset() |
| 370 |
for graph in self.graphs.values(): |
| 371 |
with contextlib.suppress(NotImplementedError): |
| 372 |
graph.source.reset() |
| 373 |
|
| 374 |
self.clock_view.set_text(ZERO_TIME) |
| 375 |
|
| 376 |
self.update_displayed_information() |
| 377 |
|
| 378 |
def on_menu_close(self): |
| 379 |
"""Return to main screen""" |
| 380 |
self.original_widget = self.main_window_w |
| 381 |
|
| 382 |
def on_graphs_menu_close(self, update): |
| 383 |
"""Return to main screen and update sensor that |
| 384 |
are active in the view""" |
| 385 |
logging.info("closing sensor menu, update=%s", update) |
| 386 |
if update: |
| 387 |
for sensor, visible_sensors in self.graphs_menu.active_sensors.items(): |
| 388 |
self.graphs[sensor].set_visible_graphs(visible_sensors) |
| 389 |
|
| 390 |
if any(visible_sensors): |
| 391 |
self.visible_graphs[sensor] = self.graphs[sensor] |
| 392 |
elif sensor in self.visible_graphs: |
| 393 |
del self.visible_graphs[sensor] |
| 394 |
self.show_graphs() |
| 395 |
|
| 396 |
self.original_widget = self.main_window_w |
| 397 |
|
| 398 |
def on_summary_menu_close(self, update): |
| 399 |
"""Return to main screen and update sensor that |
| 400 |
are active in the view""" |
| 401 |
logging.info("closing summary_menu menu, update=%s", update) |
| 402 |
if update: |
| 403 |
for sensor, visible_sensors in self.summary_menu.active_sensors.items(): |
| 404 |
self.visible_summaries[sensor].update_visibility(visible_sensors) |
| 405 |
|
| 406 |
self.main_window_w.base_widget[0].body[ |
| 407 |
self.summary_widget_index |
| 408 |
] = self._generate_summaries() |
| 409 |
|
| 410 |
self.original_widget = self.main_window_w |
| 411 |
|
| 412 |
def _open_menu_overlay(self, menu): |
| 413 |
"""Helper to open a menu overlay with cached size""" |
| 414 |
height, width = menu.get_size() |
| 415 |
self.original_widget = urwid.Overlay( |
| 416 |
menu.main_window, |
| 417 |
self.original_widget, |
| 418 |
("fixed left", 1), |
| 419 |
width, |
| 420 |
"top", |
| 421 |
height, |
| 422 |
) |
| 423 |
|
| 424 |
def on_stress_menu_open(self, widget): |
| 425 |
"""Open stress options""" |
| 426 |
self._open_menu_overlay(self.stress_menu) |
| 427 |
|
| 428 |
def on_builtin_stress_menu_open(self, widget): |
| 429 |
"""Open built-in stress options""" |
| 430 |
self._open_menu_overlay(self.builtin_stress_menu) |
| 431 |
|
| 432 |
def on_help_menu_open(self, widget): |
| 433 |
"""Open Help menu""" |
| 434 |
self._open_menu_overlay(self.help_menu) |
| 435 |
|
| 436 |
def on_about_menu_open(self, widget): |
| 437 |
"""Open About menu""" |
| 438 |
self._open_menu_overlay(self.about_menu) |
| 439 |
|
| 440 |
def on_graphs_menu_open(self, widget): |
| 441 |
"""Open Sensor menu on top of existing frame""" |
| 442 |
self._open_menu_overlay(self.graphs_menu) |
| 443 |
|
| 444 |
def on_summary_menu_open(self, widget): |
| 445 |
"""Open Sensor menu on top of existing frame""" |
| 446 |
self._open_menu_overlay(self.summary_menu) |
| 447 |
|
| 448 |
def _create_power_profile_menu(self) -> PowerProfileMenu | None: |
| 449 |
"""Create the power profile menu if at least one setting is controllable.""" |
| 450 |
available_governors = read_available(SYSFS_AVAIL_GOVERNORS) |
| 451 |
available_epp = read_available(SYSFS_AVAIL_EPP) |
| 452 |
can_write_governor = os.access(SYSFS_GOVERNOR, os.W_OK) |
| 453 |
can_write_epp = os.access(SYSFS_EPP, os.W_OK) |
| 454 |
|
| 455 |
menu = PowerProfileMenu( |
| 456 |
return_fn=self.on_menu_close, |
| 457 |
powerprofilesctl_exe=self.controller.powerprofilesctl_exe, |
| 458 |
can_write_governor=can_write_governor, |
| 459 |
can_write_epp=can_write_epp, |
| 460 |
available_governors=available_governors, |
| 461 |
available_epp=available_epp, |
| 462 |
) |
| 463 |
if not menu.is_controllable(): |
| 464 |
logging.info("Power profile menu: nothing controllable, hiding") |
| 465 |
return None |
| 466 |
return menu |
| 467 |
|
| 468 |
def on_power_profile_menu_open(self, widget): |
| 469 |
"""Open Power Profile menu""" |
| 470 |
if self.power_profile_menu is not None: |
| 471 |
self.power_profile_menu.refresh_state() |
| 472 |
self._open_menu_overlay(self.power_profile_menu) |
| 473 |
|
| 474 |
def on_mode_button(self, my_button, state): |
| 475 |
"""Notify the controller of a new mode setting.""" |
| 476 |
if state: |
| 477 |
|
| 478 |
self.controller.set_mode(my_button.get_label()) |
| 479 |
|
| 480 |
def on_unicode_checkbox(self, w=None, state=False): |
| 481 |
"""Enable smooth edges if utf-8 is supported""" |
| 482 |
logging.debug("unicode State is %s", state) |
| 483 |
|
| 484 |
|
| 485 |
self.controller.smooth_graph_mode = state |
| 486 |
if state: |
| 487 |
self.hline = urwid.AttrMap( |
| 488 |
urwid.SolidFill("\N{LOWER ONE QUARTER BLOCK}"), "line" |
| 489 |
) |
| 490 |
else: |
| 491 |
self.hline = urwid.AttrMap(urwid.SolidFill(" "), "line") |
| 492 |
|
| 493 |
for graph in self.graphs.values(): |
| 494 |
graph.set_smooth_colors(state) |
| 495 |
|
| 496 |
self.show_graphs() |
| 497 |
|
| 498 |
def on_save_settings(self, w=None): |
| 499 |
"""Calls controller save settings method""" |
| 500 |
self.controller.save_settings() |
| 501 |
|
| 502 |
def on_exit_program(self, w=None): |
| 503 |
"""Calls controller exit_program method""" |
| 504 |
self.controller.exit_program() |
| 505 |
|
| 506 |
def _generate_graph_controls(self): |
| 507 |
"""Display sidebar controls. i.e. buttons, and controls""" |
| 508 |
|
| 509 |
stress_modes = self.controller.stress_controller.get_modes() |
| 510 |
group = [] |
| 511 |
for mode in stress_modes: |
| 512 |
self.mode_buttons.append(radio_button(group, mode, self.on_mode_button)) |
| 513 |
|
| 514 |
|
| 515 |
self.mode_buttons[0].original_widget.set_state(True, do_callback=False) |
| 516 |
|
| 517 |
|
| 518 |
control_options = [] |
| 519 |
control_options.append(button("Graphs", self.on_graphs_menu_open)) |
| 520 |
control_options.append(button("Summaries", self.on_summary_menu_open)) |
| 521 |
control_options.append(button("s-tui stress", self.on_builtin_stress_menu_open)) |
| 522 |
if self.controller.stress_exe: |
| 523 |
control_options.append(button("Stress (ext)", self.on_stress_menu_open)) |
| 524 |
if self.power_profile_menu is not None: |
| 525 |
control_options.append( |
| 526 |
button("Power Profile", self.on_power_profile_menu_open) |
| 527 |
) |
| 528 |
control_options.append(button("Reset", self.on_reset_button)) |
| 529 |
control_options.append(button("Help", self.on_help_menu_open)) |
| 530 |
control_options.append(button("About", self.on_about_menu_open)) |
| 531 |
control_options.append(button("Save Settings", self.on_save_settings)) |
| 532 |
control_options.append(button("Quit", self.on_exit_program)) |
| 533 |
|
| 534 |
|
| 535 |
animate_controls = urwid.GridFlow(control_options, 18, 2, 0, "center") |
| 536 |
|
| 537 |
|
| 538 |
default_smooth = self.controller.smooth_graph_mode |
| 539 |
if urwid.get_encoding_mode() == "utf8": |
| 540 |
unicode_checkbox = urwid.CheckBox( |
| 541 |
"UTF-8", state=default_smooth, on_state_change=self.on_unicode_checkbox |
| 542 |
) |
| 543 |
|
| 544 |
self.on_unicode_checkbox(state=default_smooth) |
| 545 |
else: |
| 546 |
unicode_checkbox = urwid.Text("[N/A] UTF-8") |
| 547 |
|
| 548 |
clock_widget = [ |
| 549 |
urwid.Text(("bold text", "Stress Timer"), align="center"), |
| 550 |
self.clock_view, |
| 551 |
] |
| 552 |
|
| 553 |
controls = [urwid.Text(("bold text", "Modes"), align="center")] |
| 554 |
controls += self.mode_buttons |
| 555 |
controls += [urwid.Divider()] |
| 556 |
controls += clock_widget |
| 557 |
controls += [ |
| 558 |
urwid.Divider(), |
| 559 |
urwid.Text(("bold text", "Control Options"), align="center"), |
| 560 |
animate_controls, |
| 561 |
urwid.Divider(), |
| 562 |
urwid.Text(("bold text", "Visual Options"), align="center"), |
| 563 |
unicode_checkbox, |
| 564 |
self.refresh_rate_ctrl, |
| 565 |
urwid.Divider(), |
| 566 |
urwid.Text(("bold text", "Summaries"), align="center"), |
| 567 |
] |
| 568 |
|
| 569 |
return controls |
| 570 |
|
| 571 |
def _update_cpu_policy(self): |
| 572 |
"""Read CPU governor and energy performance preference from sysfs.""" |
| 573 |
try: |
| 574 |
self.governor_view.set_text(cat(SYSFS_GOVERNOR, binary=False).strip()) |
| 575 |
except OSError: |
| 576 |
self.governor_view.set_text("N/A") |
| 577 |
try: |
| 578 |
self.epp_view.set_text(cat(SYSFS_EPP, binary=False).strip()) |
| 579 |
except OSError: |
| 580 |
self.epp_view.set_text("N/A") |
| 581 |
|
| 582 |
@staticmethod |
| 583 |
def _generate_cpu_stats(): |
| 584 |
"""Read and display processor name""" |
| 585 |
cpu_name = urwid.Text("CPU Name N/A", align="center") |
| 586 |
try: |
| 587 |
cpu_name = urwid.Text(get_processor_name().strip(), align="center") |
| 588 |
except OSError: |
| 589 |
logging.info("CPU name not available") |
| 590 |
return [ |
| 591 |
urwid.Text(("bold text", "CPU Detected"), align="center"), |
| 592 |
cpu_name, |
| 593 |
urwid.Divider(), |
| 594 |
] |
| 595 |
|
| 596 |
def _generate_summaries(self): |
| 597 |
fixed_stats = [] |
| 598 |
for summary in self.visible_summaries.values(): |
| 599 |
fixed_stats += summary.get_text_item_list() |
| 600 |
fixed_stats += [urwid.Text("")] |
| 601 |
|
| 602 |
|
| 603 |
return urwid.Pile(fixed_stats) |
| 604 |
|
| 605 |
def show_graphs(self): |
| 606 |
"""Show a pile of the graph selected for display""" |
| 607 |
self.graph_place_holder.original_widget = urwid.Pile( |
| 608 |
list(self.visible_graphs.values()) |
| 609 |
) |
| 610 |
|
| 611 |
def main_window(self): |
| 612 |
|
| 613 |
self.graphs = OrderedDict() |
| 614 |
self.summaries = OrderedDict() |
| 615 |
|
| 616 |
for source in self.controller.sources: |
| 617 |
source_name = source.get_source_name() |
| 618 |
color_pallet = source.get_pallet() |
| 619 |
alert_pallet = source.get_alert_pallet() |
| 620 |
self.graphs[source_name] = BarGraphVector( |
| 621 |
source, |
| 622 |
color_pallet, |
| 623 |
len(source.get_sensor_list()), |
| 624 |
self.graphs_menu.active_sensors[source_name], |
| 625 |
alert_colors=alert_pallet, |
| 626 |
) |
| 627 |
if self.controller.script_hooks_enabled: |
| 628 |
source.add_edge_hook( |
| 629 |
self.controller.script_loader.load_script( |
| 630 |
source.__class__.__name__, HOOK_INTERVAL |
| 631 |
) |
| 632 |
) |
| 633 |
|
| 634 |
self.summaries[source_name] = SummaryTextList( |
| 635 |
self.graphs[source_name].source, |
| 636 |
self.summary_menu.active_sensors[source_name], |
| 637 |
) |
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
self.visible_graphs = OrderedDict( |
| 642 |
(key, val) |
| 643 |
for key, val in self.graphs.items() |
| 644 |
if val.get_is_available() and any(self.graphs_menu.active_sensors[key]) |
| 645 |
) |
| 646 |
|
| 647 |
self.visible_summaries = OrderedDict( |
| 648 |
(key, val) for key, val in self.summaries.items() if val.get_is_available() |
| 649 |
) |
| 650 |
|
| 651 |
cpu_stats = self._generate_cpu_stats() |
| 652 |
graph_controls = self._generate_graph_controls() |
| 653 |
summaries = self._generate_summaries() |
| 654 |
|
| 655 |
cpu_policy = [ |
| 656 |
urwid.Text(("bold text", "Governor"), align="center"), |
| 657 |
self.governor_view, |
| 658 |
urwid.Text(""), |
| 659 |
urwid.Text(("bold text", "Energy Pref"), align="center"), |
| 660 |
self.epp_view, |
| 661 |
urwid.Divider(), |
| 662 |
] |
| 663 |
text_col = ViListBox( |
| 664 |
urwid.SimpleListWalker( |
| 665 |
cpu_stats + cpu_policy + graph_controls + [summaries] |
| 666 |
) |
| 667 |
) |
| 668 |
|
| 669 |
vline = urwid.AttrMap(urwid.SolidFill("|"), "line") |
| 670 |
widget = urwid.Columns( |
| 671 |
[ |
| 672 |
("fixed", 20, text_col), |
| 673 |
("fixed", 1, vline), |
| 674 |
("weight", 2, self.graph_place_holder), |
| 675 |
], |
| 676 |
dividechars=0, |
| 677 |
focus_column=0, |
| 678 |
) |
| 679 |
|
| 680 |
widget = urwid.Padding(widget, ("fixed left", 1), ("fixed right", 1)) |
| 681 |
self.main_window_w = widget |
| 682 |
|
| 683 |
base = self.main_window_w.base_widget[0].body |
| 684 |
self.summary_widget_index = len(base) - 1 |
| 685 |
logging.debug("Pile index: %s", self.summary_widget_index) |
| 686 |
|
| 687 |
return self.main_window_w |
| 688 |
|
| 689 |
|
| 690 |
class GraphController: |
| 691 |
""" |
| 692 |
The GraphController holds the state of the graph, this includes the current |
| 693 |
* Operation mode (stress/no-stress) |
| 694 |
* Current selected graphs for display, |
| 695 |
* The state of the radio and selector buttons |
| 696 |
* The current graphs refresh rate |
| 697 |
|
| 698 |
The controller is generated once, and is updated according to inputs |
| 699 |
|
| 700 |
GraphController and GraphView are closely intertwined, there is a reference |
| 701 |
to each in the other. |
| 702 |
This is not perfect, but changes in the View reflect on the graph state and |
| 703 |
visa versa |
| 704 |
""" |
| 705 |
|
| 706 |
def _load_config(self, t_thresh): |
| 707 |
""" |
| 708 |
Uses configurations defined by user to configure sources for display. |
| 709 |
This should be the only place where sources are initiated |
| 710 |
|
| 711 |
This returns a list of sources after configurations are applied |
| 712 |
""" |
| 713 |
|
| 714 |
if not user_config_dir_exists(): |
| 715 |
user_config_dir = make_user_config_dir() |
| 716 |
else: |
| 717 |
user_config_dir = get_user_config_dir() |
| 718 |
|
| 719 |
if user_config_dir is None: |
| 720 |
logging.warning( |
| 721 |
"Failed to find or create scripts directory,\ |
| 722 |
proceeding without scripting support" |
| 723 |
) |
| 724 |
self.script_hooks_enabled = False |
| 725 |
else: |
| 726 |
self.script_loader = ScriptHookLoader(user_config_dir) |
| 727 |
|
| 728 |
|
| 729 |
self.conf: configparser.ConfigParser | None = None |
| 730 |
if user_config_file_exists(): |
| 731 |
self.conf = configparser.ConfigParser(delimiters="=") |
| 732 |
self.conf.read(get_user_config_file()) |
| 733 |
else: |
| 734 |
logging.debug("Config file not found") |
| 735 |
|
| 736 |
|
| 737 |
if self.conf is not None: |
| 738 |
try: |
| 739 |
self.refresh_rate = str(self.conf.getfloat("GraphControl", "refresh")) |
| 740 |
logging.debug("User refresh rate: %s", self.refresh_rate) |
| 741 |
except ( |
| 742 |
ValueError, |
| 743 |
configparser.NoOptionError, |
| 744 |
configparser.NoSectionError, |
| 745 |
): |
| 746 |
logging.debug("No refresh rate configured") |
| 747 |
|
| 748 |
try: |
| 749 |
if self.conf.getboolean("GraphControl", "UTF8"): |
| 750 |
self.smooth_graph_mode = True |
| 751 |
else: |
| 752 |
logging.debug( |
| 753 |
"UTF8 selected as %s", self.conf.get("GraphControl", "UTF8") |
| 754 |
) |
| 755 |
except ( |
| 756 |
ValueError, |
| 757 |
configparser.NoOptionError, |
| 758 |
configparser.NoSectionError, |
| 759 |
): |
| 760 |
logging.debug("No user config for utf8") |
| 761 |
|
| 762 |
if t_thresh is None: |
| 763 |
try: |
| 764 |
self.temp_thresh = self.conf.get("GraphControl", "TTHRESH") |
| 765 |
logging.debug("Temperature threshold set to %s", self.temp_thresh) |
| 766 |
except ( |
| 767 |
ValueError, |
| 768 |
configparser.NoOptionError, |
| 769 |
configparser.NoSectionError, |
| 770 |
): |
| 771 |
logging.debug("No user config for temp threshold") |
| 772 |
|
| 773 |
if t_thresh is not None: |
| 774 |
self.temp_thresh = t_thresh |
| 775 |
|
| 776 |
|
| 777 |
possible_sources = [ |
| 778 |
TempSource(self.temp_thresh), |
| 779 |
FreqSource(), |
| 780 |
UtilSource(), |
| 781 |
RaplPowerSource(), |
| 782 |
FanSource(), |
| 783 |
] |
| 784 |
|
| 785 |
|
| 786 |
sources = [ |
| 787 |
x.get_source_name() for x in possible_sources if x.get_is_available() |
| 788 |
] |
| 789 |
if self.conf is not None: |
| 790 |
for source in sources: |
| 791 |
try: |
| 792 |
for option_name, option_value in self.conf.items( |
| 793 |
source + ",Graphs" |
| 794 |
): |
| 795 |
self.graphs_default_conf[source][option_name] = str_to_bool( |
| 796 |
option_value |
| 797 |
) |
| 798 |
for option_name, option_value in self.conf.items( |
| 799 |
source + ",Summaries" |
| 800 |
): |
| 801 |
self.summary_default_conf[source][option_name] = str_to_bool( |
| 802 |
option_value |
| 803 |
) |
| 804 |
except ( |
| 805 |
ValueError, |
| 806 |
configparser.NoOptionError, |
| 807 |
configparser.NoSectionError, |
| 808 |
): |
| 809 |
logging.debug("Error reading sensors config") |
| 810 |
|
| 811 |
return possible_sources |
| 812 |
|
| 813 |
def _config_stress(self): |
| 814 |
"""Configures the possible stress processes and modes""" |
| 815 |
|
| 816 |
self.stress_exe = None |
| 817 |
stress_installed = False |
| 818 |
self.stress_exe = which("stress") |
| 819 |
if self.stress_exe: |
| 820 |
stress_installed = True |
| 821 |
else: |
| 822 |
self.stress_exe = which("stress-ng") |
| 823 |
if self.stress_exe: |
| 824 |
stress_installed = True |
| 825 |
|
| 826 |
return StressController(stress_installed) |
| 827 |
|
| 828 |
def __init__(self, args): |
| 829 |
self.conf = None |
| 830 |
self.script_hooks_enabled = True |
| 831 |
self.script_loader = None |
| 832 |
|
| 833 |
self.refresh_rate = args.refresh_rate |
| 834 |
|
| 835 |
self.smooth_graph_mode = False |
| 836 |
|
| 837 |
self.summary_default_conf = defaultdict(dict) |
| 838 |
self.graphs_default_conf = defaultdict(dict) |
| 839 |
|
| 840 |
self.temp_thresh = None |
| 841 |
|
| 842 |
possible_sources = self._load_config(args.t_thresh) |
| 843 |
|
| 844 |
|
| 845 |
self.args = args |
| 846 |
|
| 847 |
self.stress_controller = self._config_stress() |
| 848 |
|
| 849 |
self.powerprofilesctl_exe = which("powerprofilesctl") |
| 850 |
|
| 851 |
self.handle_mouse = not args.no_mouse |
| 852 |
|
| 853 |
self.stress_start_time = 0 |
| 854 |
|
| 855 |
|
| 856 |
self.sources = [s for s in possible_sources if s.get_is_available()] |
| 857 |
|
| 858 |
|
| 859 |
self.view = GraphView(self) |
| 860 |
|
| 861 |
|
| 862 |
self.csv_file = None |
| 863 |
self.save_csv = args.csv |
| 864 |
if args.csv_file is not None: |
| 865 |
self.csv_file = args.csv_file |
| 866 |
logging.info("Printing output to csv %s", self.csv_file) |
| 867 |
elif args.csv_file is None and args.csv: |
| 868 |
self.csv_file = DEFAULT_CSV_FILE |
| 869 |
|
| 870 |
self.debug_run_counter = 0 |
| 871 |
|
| 872 |
def set_mode(self, mode): |
| 873 |
"""Allow our view to set the mode.""" |
| 874 |
self.stress_controller.set_mode(mode) |
| 875 |
self.update_stress_mode() |
| 876 |
|
| 877 |
def main(self): |
| 878 |
"""Starts the main loop and graph animation""" |
| 879 |
loop = MainLoop( |
| 880 |
self.view, |
| 881 |
DEFAULT_PALETTE, |
| 882 |
handle_mouse=self.handle_mouse, |
| 883 |
|
| 884 |
) |
| 885 |
self.view.show_graphs() |
| 886 |
self.animate_graph(loop) |
| 887 |
try: |
| 888 |
loop.run() |
| 889 |
except ZeroDivisionError as err: |
| 890 |
|
| 891 |
|
| 892 |
logging.debug("Some stat caused divide by zero exception. Exiting") |
| 893 |
logging.error(err, exc_info=True) |
| 894 |
print(ERROR_MESSAGE) |
| 895 |
except AttributeError as err: |
| 896 |
|
| 897 |
|
| 898 |
logging.debug("Catch attribute Error in urwid and restart") |
| 899 |
logging.debug(err, exc_info=True) |
| 900 |
self.main() |
| 901 |
except psutil.NoSuchProcess as err: |
| 902 |
|
| 903 |
|
| 904 |
logging.error("No such process error") |
| 905 |
logging.error(err, exc_info=True) |
| 906 |
print(ERROR_MESSAGE) |
| 907 |
|
| 908 |
def update_stress_mode(self): |
| 909 |
"""Updates stress mode according to radio buttons state""" |
| 910 |
|
| 911 |
self.stress_controller.kill_stress_process() |
| 912 |
|
| 913 |
|
| 914 |
self.view.clock_view.set_text(ZERO_TIME) |
| 915 |
self.stress_start_time = timeit.default_timer() |
| 916 |
|
| 917 |
if self.stress_controller.get_current_mode() == "s-tui stress": |
| 918 |
num_workers = self.view.builtin_stress_menu.get_num_workers() |
| 919 |
strategy = self.view.builtin_stress_menu.get_strategy() |
| 920 |
self.stress_controller.start_builtin_stress(num_workers, strategy) |
| 921 |
|
| 922 |
elif self.stress_controller.get_current_mode() == "Stress (ext)": |
| 923 |
stress_cmd = self.view.stress_menu.get_stress_cmd() |
| 924 |
self.stress_controller.start_stress(stress_cmd) |
| 925 |
|
| 926 |
def save_settings(self): |
| 927 |
"""Save the current configuration to a user config file""" |
| 928 |
|
| 929 |
sources_by_name = {s.get_source_name(): s for s in self.sources} |
| 930 |
|
| 931 |
def _save_displayed_setting(conf, submenu): |
| 932 |
items = [] |
| 933 |
if submenu == "Graphs": |
| 934 |
items = self.view.graphs_menu.active_sensors.items() |
| 935 |
elif submenu == "Summaries": |
| 936 |
items = self.view.summary_menu.active_sensors.items() |
| 937 |
|
| 938 |
for source, visible_sensors in items: |
| 939 |
section = source + "," + submenu |
| 940 |
conf.add_section(section) |
| 941 |
|
| 942 |
logging.debug("Saving settings for %s", source) |
| 943 |
logging.debug("Visible sensors %s", visible_sensors) |
| 944 |
curr_sensor = sources_by_name.get(source) |
| 945 |
if curr_sensor is None: |
| 946 |
continue |
| 947 |
sensor_list = curr_sensor.get_sensor_list() |
| 948 |
for sensor_id, sensor in enumerate(sensor_list): |
| 949 |
try: |
| 950 |
conf.set(section, sensor, str(visible_sensors[sensor_id])) |
| 951 |
except IndexError: |
| 952 |
conf.set(section, sensor, str(True)) |
| 953 |
|
| 954 |
if not user_config_dir_exists(): |
| 955 |
make_user_config_dir() |
| 956 |
|
| 957 |
conf = configparser.ConfigParser(delimiters="=") |
| 958 |
config_file = get_user_config_file() |
| 959 |
with open(config_file, "w") as cfgfile: |
| 960 |
conf.add_section("GraphControl") |
| 961 |
|
| 962 |
conf.set("GraphControl", "refresh", str(self.refresh_rate)) |
| 963 |
|
| 964 |
conf.set("GraphControl", "UTF8", str(self.smooth_graph_mode)) |
| 965 |
|
| 966 |
if self.temp_thresh: |
| 967 |
conf.set("GraphControl", "TTHRESH", str(self.temp_thresh)) |
| 968 |
|
| 969 |
_save_displayed_setting(conf, "Graphs") |
| 970 |
_save_displayed_setting(conf, "Summaries") |
| 971 |
conf.write(cfgfile) |
| 972 |
|
| 973 |
def exit_program(self): |
| 974 |
"""Kill all stress operations upon exit""" |
| 975 |
self.stress_controller.kill_stress_process() |
| 976 |
raise urwid.ExitMainLoop() |
| 977 |
|
| 978 |
def animate_graph(self, loop, user_data=None): |
| 979 |
""" |
| 980 |
Update the graph and schedule the next update |
| 981 |
This is where the magic happens |
| 982 |
""" |
| 983 |
self.view.update_displayed_information() |
| 984 |
|
| 985 |
|
| 986 |
if (self.save_csv or self.csv_file is not None) and self.csv_file is not None: |
| 987 |
output_to_csv(self.view.summaries, self.csv_file) |
| 988 |
|
| 989 |
|
| 990 |
self.animate_alarm = loop.set_alarm_in( |
| 991 |
float(self.refresh_rate), self.animate_graph |
| 992 |
) |
| 993 |
|
| 994 |
if self.args.debug_run: |
| 995 |
|
| 996 |
self.debug_run_counter += int(float(self.refresh_rate)) |
| 997 |
if self.debug_run_counter >= 8: |
| 998 |
self.exit_program() |
| 999 |
|
| 1000 |
|
| 1001 |
def main(): |
| 1002 |
args = get_args() |
| 1003 |
|
| 1004 |
if args.version: |
| 1005 |
print(VERSION_MESSAGE) |
| 1006 |
sys.exit(0) |
| 1007 |
|
| 1008 |
|
| 1009 |
log_file = DEFAULT_LOG_FILE |
| 1010 |
if args.debug_run: |
| 1011 |
args.debug = True |
| 1012 |
|
| 1013 |
log_formatter = logging.Formatter( |
| 1014 |
"%(asctime)s [%(funcName)s()] [%(levelname)-5.5s] %(message)s" |
| 1015 |
) |
| 1016 |
root_logger = logging.getLogger() |
| 1017 |
|
| 1018 |
if args.debug or args.debug_file is not None: |
| 1019 |
level = logging.DEBUG |
| 1020 |
if args.debug_file is not None: |
| 1021 |
log_file = args.debug_file |
| 1022 |
file_handler = logging.FileHandler(log_file) |
| 1023 |
file_handler.setFormatter(log_formatter) |
| 1024 |
root_logger.addHandler(file_handler) |
| 1025 |
else: |
| 1026 |
level = logging.ERROR |
| 1027 |
root_logger.setLevel(level) |
| 1028 |
|
| 1029 |
if args.terminal or args.json: |
| 1030 |
logging.info("Printing single line to terminal") |
| 1031 |
sources = [ |
| 1032 |
FreqSource(), |
| 1033 |
TempSource(), |
| 1034 |
UtilSource(), |
| 1035 |
RaplPowerSource(), |
| 1036 |
FanSource(), |
| 1037 |
] |
| 1038 |
if args.terminal: |
| 1039 |
output_to_terminal(sources) |
| 1040 |
elif args.json: |
| 1041 |
output_to_json(sources) |
| 1042 |
|
| 1043 |
global graph_controller |
| 1044 |
graph_controller = GraphController(args) |
| 1045 |
atexit.register(graph_controller.stress_controller.kill_stress_process) |
| 1046 |
graph_controller.main() |
| 1047 |
|
| 1048 |
|
| 1049 |
def get_args(): |
| 1050 |
parser = argparse.ArgumentParser( |
| 1051 |
description=HELP_MESSAGE, formatter_class=argparse.RawTextHelpFormatter |
| 1052 |
) |
| 1053 |
|
| 1054 |
parser.add_argument( |
| 1055 |
"-d", |
| 1056 |
"--debug", |
| 1057 |
default=False, |
| 1058 |
action="store_true", |
| 1059 |
help="Output debug log to _s-tui.log", |
| 1060 |
) |
| 1061 |
parser.add_argument( |
| 1062 |
"--debug-file", |
| 1063 |
default=None, |
| 1064 |
help="Use a custom debug file. Default: " + "_s-tui.log", |
| 1065 |
) |
| 1066 |
|
| 1067 |
parser.add_argument( |
| 1068 |
"-dr", |
| 1069 |
"--debug_run", |
| 1070 |
default=False, |
| 1071 |
action="store_true", |
| 1072 |
help="Run for 5 seconds and quit", |
| 1073 |
) |
| 1074 |
parser.add_argument( |
| 1075 |
"-c", "--csv", action="store_true", default=False, help="Save stats to csv file" |
| 1076 |
) |
| 1077 |
parser.add_argument( |
| 1078 |
"--csv-file", |
| 1079 |
default=None, |
| 1080 |
help="Use a custom CSV file. Default: " + "s-tui_log_<TIME>.csv", |
| 1081 |
) |
| 1082 |
parser.add_argument( |
| 1083 |
"-t", |
| 1084 |
"--terminal", |
| 1085 |
action="store_true", |
| 1086 |
default=False, |
| 1087 |
help="Display a single line of stats without tui", |
| 1088 |
) |
| 1089 |
parser.add_argument( |
| 1090 |
"-j", |
| 1091 |
"--json", |
| 1092 |
action="store_true", |
| 1093 |
default=False, |
| 1094 |
help="Display a single line of stats in JSON format", |
| 1095 |
) |
| 1096 |
parser.add_argument( |
| 1097 |
"-nm", |
| 1098 |
"--no-mouse", |
| 1099 |
action="store_true", |
| 1100 |
default=False, |
| 1101 |
help="Disable Mouse for TTY systems", |
| 1102 |
) |
| 1103 |
parser.add_argument( |
| 1104 |
"-v", "--version", default=False, action="store_true", help="Display version" |
| 1105 |
) |
| 1106 |
parser.add_argument( |
| 1107 |
"-tt", |
| 1108 |
"--t_thresh", |
| 1109 |
default=None, |
| 1110 |
help="High Temperature threshold. Default: 80", |
| 1111 |
) |
| 1112 |
parser.add_argument( |
| 1113 |
"-r", |
| 1114 |
"--refresh-rate", |
| 1115 |
dest="refresh_rate", |
| 1116 |
default="2.0", |
| 1117 |
help="Refresh rate in seconds. Default: 2.0", |
| 1118 |
) |
| 1119 |
args = parser.parse_args() |
| 1120 |
return args |
| 1121 |
|
| 1122 |
|
| 1123 |
if __name__ == "__main__": |
| 1124 |
main() |