brainframe-sys-tools 0.5.3__tar.gz → 0.5.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/PKG-INFO +42 -4
  2. brainframe_sys_tools-0.5.5/README.md +36 -0
  3. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/__init__.py +7 -0
  4. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/bf_info.py +10 -8
  5. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/bf_service_monitor.py +12 -8
  6. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/bf_ssh_tunnel.py +10 -8
  7. brainframe_sys_tools-0.5.5/brainframe_sys_tools/brainframe_monitor/__pycache__/benchmarker.cpython-312.pyc +0 -0
  8. brainframe_sys_tools-0.5.5/brainframe_sys_tools/brainframe_monitor/__pycache__/brainframe_monitor.cpython-312.pyc +0 -0
  9. brainframe_sys_tools-0.5.5/brainframe_sys_tools/brainframe_monitor/__pycache__/fake_screen.cpython-312.pyc +0 -0
  10. brainframe_sys_tools-0.5.5/brainframe_sys_tools/brainframe_monitor/__pycache__/report.cpython-312.pyc +0 -0
  11. brainframe_sys_tools-0.5.5/brainframe_sys_tools/brainframe_monitor/__pycache__/system_monitor.cpython-312.pyc +0 -0
  12. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/brainframe_monitor/benchmarker.py +7 -2
  13. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/brainframe_monitor/brainframe_monitor.py +27 -18
  14. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/cli.py +5 -1
  15. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/command_utils.py +6 -2
  16. brainframe_sys_tools-0.5.5/brainframe_sys_tools/perf_monitor.py +524 -0
  17. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/translations/portal.en.yml +5 -4
  18. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/pyproject.toml +4 -3
  19. brainframe_sys_tools-0.5.3/brainframe_sys_tools/brainframe_monitor/__pycache__/benchmarker.cpython-38.pyc +0 -0
  20. brainframe_sys_tools-0.5.3/brainframe_sys_tools/brainframe_monitor/__pycache__/curses_utils.cpython-38.pyc +0 -0
  21. brainframe_sys_tools-0.5.3/brainframe_sys_tools/brainframe_monitor/__pycache__/fake_screen.cpython-38.pyc +0 -0
  22. brainframe_sys_tools-0.5.3/brainframe_sys_tools/brainframe_monitor/__pycache__/report.cpython-38.pyc +0 -0
  23. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/COPYING +0 -0
  24. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/brainframe_monitor/curses_utils.py +0 -0
  25. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/brainframe_monitor/fake_screen.py +0 -0
  26. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/brainframe_monitor/report.py +0 -0
  27. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/check_memory.py +0 -0
  28. {brainframe_sys_tools-0.5.3 → brainframe_sys_tools-0.5.5}/brainframe_sys_tools/print_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: brainframe-sys-tools
3
- Version: 0.5.3
3
+ Version: 0.5.5
4
4
  Summary: This is the package including tools for BrainFrame developers to monitor and debug the system.
5
5
  License: BSD License
6
6
  Author: Stephen Li
@@ -13,12 +13,50 @@ Classifier: Programming Language :: Python :: 3.9
13
13
  Classifier: Programming Language :: Python :: 3.10
14
14
  Classifier: Programming Language :: Python :: 3.11
15
15
  Classifier: Programming Language :: Python :: 3.12
16
- Classifier: Programming Language :: Python :: 3.13
17
16
  Requires-Dist: PyYAML (>=6.0.2,<7.0.0)
18
17
  Requires-Dist: apscheduler (>=3.10.4,<4.0.0)
19
- Requires-Dist: brainframe-api (>=0.30.3,<0.31.0)
20
- Requires-Dist: brainframe_apps (>=0.5.3,<0.6.0)
18
+ Requires-Dist: brainframe-api (>=0.30.4,<0.31.0)
19
+ Requires-Dist: brainframe_apps (>=0.5.4,<0.6.0)
21
20
  Requires-Dist: psutil (>=5.8.0,<6.0.0)
22
21
  Requires-Dist: python_i18n (>=0.3.9,<0.4.0)
23
22
  Requires-Dist: requests (>=2.32.3,<3.0.0)
24
23
  Requires-Dist: tabulate (>=0.8.9,<0.9.0)
24
+ Description-Content-Type: text/markdown
25
+
26
+ # brainframe-sys-tools
27
+
28
+ Python CLI tools for monitoring and debugging BrainFrame system deployment.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install brainframe-sys-tools
34
+ ```
35
+
36
+ ## Usage
37
+
38
+ ```bash
39
+ brainframe-sys-tools <command> [options]
40
+ ```
41
+
42
+ ### Commands
43
+
44
+ - `perf_monitor` - Monitor CPU, GPU, memory, storage, and temperatures
45
+ - `fps_monitor` - Monitor BrainFrame stream FPS and throughput
46
+ - `service_monitor` - Monitor BrainFrame service health
47
+ - `sys_info` - Display system information
48
+ - `ssh_tunnel` - Create SSH tunnels
49
+
50
+ ### Example
51
+
52
+ ```bash
53
+ brainframe-sys-tools perf_monitor
54
+ brainframe-sys-tools fps_monitor --server-url http://localhost
55
+ ```
56
+
57
+ ## Help
58
+
59
+ ```bash
60
+ brainframe-sys-tools <command> --help
61
+ ```
62
+
@@ -0,0 +1,36 @@
1
+ # brainframe-sys-tools
2
+
3
+ Python CLI tools for monitoring and debugging BrainFrame system deployment.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install brainframe-sys-tools
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```bash
14
+ brainframe-sys-tools <command> [options]
15
+ ```
16
+
17
+ ### Commands
18
+
19
+ - `perf_monitor` - Monitor CPU, GPU, memory, storage, and temperatures
20
+ - `fps_monitor` - Monitor BrainFrame stream FPS and throughput
21
+ - `service_monitor` - Monitor BrainFrame service health
22
+ - `sys_info` - Display system information
23
+ - `ssh_tunnel` - Create SSH tunnels
24
+
25
+ ### Example
26
+
27
+ ```bash
28
+ brainframe-sys-tools perf_monitor
29
+ brainframe-sys-tools fps_monitor --server-url http://localhost
30
+ ```
31
+
32
+ ## Help
33
+
34
+ ```bash
35
+ brainframe-sys-tools <command> --help
36
+ ```
@@ -1,5 +1,12 @@
1
+ try:
2
+ from importlib.metadata import version
3
+ __version__ = version("brainframe-sys-tools")
4
+ except Exception:
5
+ __version__ = "unknown"
6
+
1
7
  from .cli import cli_main
2
8
  from .brainframe_monitor.brainframe_monitor import fps_monitor
9
+ from .perf_monitor import perf_monitor
3
10
  from .bf_info import sys_info
4
11
  from .bf_service_monitor import service_monitor
5
12
  from .bf_ssh_tunnel import ssh_tunnel
@@ -8,8 +8,10 @@ from argparse import ArgumentParser
8
8
 
9
9
  import requests
10
10
 
11
- from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
12
-
11
+ try:
12
+ from .command_utils import command, subcommand_parse_args, by_name
13
+ except ImportError:
14
+ from command_utils import command, subcommand_parse_args, by_name
13
15
 
14
16
  header = [
15
17
  "Copyright (c) 2021 Dilili Labs, Inc. All rights reserved.\n\n"
@@ -95,9 +97,8 @@ def _parse_args():
95
97
  parser.add_argument(
96
98
  "-f", "--file", default="sys.info", help="The output system info file name"
97
99
  )
98
- args = subcommand_parse_args(parser)
99
100
 
100
- return args
101
+ return parser
101
102
 
102
103
 
103
104
  def save_sys_info(log_filename):
@@ -142,9 +143,10 @@ def save_sys_info(log_filename):
142
143
  file.close()
143
144
 
144
145
 
145
- @command("sys_info")
146
- def sys_info():
147
- args = _parse_args()
146
+ @command("sys-info")
147
+ def sys_info(is_command=True):
148
+ parser = _parse_args()
149
+ args = subcommand_parse_args(parser, is_command)
148
150
 
149
151
  save_sys_info(args.file)
150
152
 
@@ -152,4 +154,4 @@ def sys_info():
152
154
 
153
155
 
154
156
  if __name__ == "__main__":
155
- by_name["sys_info"]()
157
+ by_name["sys-info"](False)
@@ -12,8 +12,12 @@ from typing import Callable
12
12
 
13
13
  from brainframe.api import BrainFrameAPI
14
14
 
15
- from brainframe_sys_tools.bf_info import save_sys_info
16
- from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
15
+ try:
16
+ from .bf_info import save_sys_info
17
+ from .command_utils import command, subcommand_parse_args, by_name
18
+ except ImportError:
19
+ from bf_info import save_sys_info
20
+ from command_utils import command, subcommand_parse_args, by_name
17
21
 
18
22
  from apscheduler.schedulers.background import BackgroundScheduler
19
23
  from apscheduler.triggers.cron import CronTrigger
@@ -293,13 +297,13 @@ def _parse_args():
293
297
  When you use an asterisk (*) in any of these fields, it represents 'every'.""",
294
298
  )
295
299
 
296
- args = subcommand_parse_args(parser)
297
- return args
300
+ return parser
298
301
 
299
302
 
300
- @command("service_monitor")
301
- def service_monitor():
302
- args = _parse_args()
303
+ @command("service-monitor")
304
+ def service_monitor(is_command=True):
305
+ parser = _parse_args()
306
+ args = subcommand_parse_args(parser, is_command)
303
307
 
304
308
  # if restart_cron is set, check if cron string is fine.
305
309
  if args.restart_cron:
@@ -340,4 +344,4 @@ def service_monitor():
340
344
 
341
345
 
342
346
  if __name__ == "__main__":
343
- by_name["service_monitor"]()
347
+ by_name["service-monitor"](False)
@@ -5,7 +5,10 @@
5
5
  import subprocess
6
6
  from argparse import ArgumentParser
7
7
 
8
- from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
8
+ try:
9
+ from .command_utils import command, subcommand_parse_args, by_name
10
+ except ImportError:
11
+ from command_utils import command, subcommand_parse_args, by_name
9
12
 
10
13
 
11
14
  def _parse_args():
@@ -52,9 +55,7 @@ def _parse_args():
52
55
  Use muliple -o to specify more options, for example '-o ServerAliveInterval=120 -o ServerAliveCountMax=3'.",
53
56
  )
54
57
 
55
- args = subcommand_parse_args(parser)
56
-
57
- return args
58
+ return parser
58
59
 
59
60
 
60
61
  def run_command_list(commandlst):
@@ -74,9 +75,10 @@ def run_command_list(commandlst):
74
75
  print(" Process was interrupted by user")
75
76
 
76
77
 
77
- @command("ssh_tunnel")
78
- def ssh_tunnel():
79
- args = _parse_args()
78
+ @command("ssh-tunnel")
79
+ def ssh_tunnel(is_command=True):
80
+ parser = _parse_args()
81
+ args = subcommand_parse_args(parser, is_command)
80
82
 
81
83
  # Build the SSH command
82
84
  ssh_command = ["ssh", "-N", "-p", args.port]
@@ -101,4 +103,4 @@ def ssh_tunnel():
101
103
 
102
104
 
103
105
  if __name__ == "__main__":
104
- by_name["ssh_tunnel"]()
106
+ by_name["ssh-tunnel"](False)
@@ -9,8 +9,13 @@ from time import sleep
9
9
 
10
10
  from brainframe.api import BrainFrameAPI, bf_errors
11
11
  from brainframe.api.stubs.zone_statuses import ZONE_STATUS_STREAM_TYPE
12
- from brainframe_sys_tools.brainframe_monitor.curses_utils import plot
13
- from brainframe_sys_tools.brainframe_monitor.report import Report
12
+ try:
13
+ from .curses_utils import plot
14
+ from .report import Report
15
+ except ImportError:
16
+ from curses_utils import plot
17
+ from report import Report
18
+
14
19
  from tabulate import tabulate
15
20
  from brainframe_apps.list_stream import stream_status
16
21
  from brainframe_apps.fps_report import (
@@ -5,18 +5,33 @@
5
5
 
6
6
  import curses
7
7
  from argparse import ArgumentParser
8
-
9
- from brainframe_sys_tools.brainframe_monitor.benchmarker import Benchmarker
10
- from brainframe_sys_tools.brainframe_monitor.fake_screen import FakeScreen
11
- from brainframe_sys_tools.brainframe_monitor.report import Report
12
8
  from datetime import datetime
13
- from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
14
9
 
10
+ try:
11
+ from .benchmarker import Benchmarker
12
+ from .fake_screen import FakeScreen
13
+ from .report import Report
14
+ from ..command_utils import command, subcommand_parse_args, by_name
15
+ except ImportError:
16
+ from benchmarker import Benchmarker
17
+ from fake_screen import FakeScreen
18
+ from report import Report
19
+
20
+ import sys
21
+ from pathlib import Path
22
+ sys.path.insert(0, str(Path(__file__).parent.parent))
23
+ from command_utils import command, subcommand_parse_args, by_name
24
+
25
+ @command("fps-monitor")
26
+ def fps_monitor(is_command=True):
27
+ version = "v2.1"
28
+ parser = _parse_args(version)
29
+ args = subcommand_parse_args(parser, is_command)
30
+
31
+ if args.version:
32
+ print(version)
33
+ exit(0)
15
34
 
16
- @command("fps_monitor")
17
- def fps_monitor():
18
- version = "v2.0"
19
- args = _parse_args(version)
20
35
  no_screen = args.no_screen
21
36
 
22
37
  report = Report(
@@ -78,7 +93,7 @@ def _parse_args(version):
78
93
  )
79
94
  parser.add_argument(
80
95
  "--out",
81
- default="brainframe_monitor.fps_history",
96
+ default="brainframe_fps_history",
82
97
  help="FPS throughput history will be saved in an output file.",
83
98
  )
84
99
  parser.add_argument(
@@ -92,14 +107,8 @@ def _parse_args(version):
92
107
  "--version", action="store_true", help="Returns the version of the script"
93
108
  )
94
109
 
95
- args = subcommand_parse_args(parser)
96
-
97
- if args.version:
98
- print(version)
99
- exit(0)
100
-
101
- return args
110
+ return parser
102
111
 
103
112
 
104
113
  if __name__ == "__main__":
105
- by_name["fps_monitor"]()
114
+ by_name["fps-monitor"](False)
@@ -8,7 +8,11 @@ from argparse import ArgumentParser
8
8
 
9
9
  import i18n
10
10
  import yaml
11
- from brainframe_sys_tools import command_utils, print_utils
11
+
12
+ try:
13
+ from . import command_utils, print_utils
14
+ except ImportError:
15
+ import command_utils, print_utils
12
16
 
13
17
 
14
18
  def add_translations(translations, prefix=""):
@@ -14,8 +14,12 @@ def command(name):
14
14
  return wrapper
15
15
 
16
16
 
17
- def subcommand_parse_args(parser: ArgumentParser):
18
- arg_list = sys.argv[2:]
17
+ def subcommand_parse_args(parser: ArgumentParser, is_command):
18
+ if is_command:
19
+ arg_list = sys.argv[2:]
20
+ else:
21
+ arg_list = sys.argv[1:]
22
+
19
23
  args = parser.parse_args(arg_list)
20
24
 
21
25
  # Run in non-interactive mode if any flags were provided
@@ -0,0 +1,524 @@
1
+ #!/usr/bin/env python3
2
+ import time
3
+ from datetime import datetime
4
+ import os
5
+ import psutil
6
+ import subprocess
7
+ import re
8
+ import json
9
+ import threading
10
+ import sys
11
+ import logging
12
+ import argparse
13
+ # Platform-specific modules for non-blocking keyboard input
14
+ try:
15
+ import tty
16
+ import termios
17
+ import select
18
+ except ImportError:
19
+ # This will be handled for non-posix systems like Windows
20
+ pass
21
+
22
+ from typing import List, Dict, Optional, Tuple
23
+
24
+ try:
25
+ from .command_utils import command, subcommand_parse_args, by_name
26
+ except ImportError:
27
+ from command_utils import command, subcommand_parse_args, by_name
28
+
29
+ # Threshold for triggering the high memory warning.
30
+ # 95% means the warning will show when available memory is 5% or less.
31
+ HIGH_MEMORY_THRESHOLD_PERCENT = 95.0
32
+
33
+ class PerfMonitor:
34
+ """
35
+ A modular class to fetch system resource usage statistics. It runs
36
+ background threads for continuous iGPU and keyboard monitoring.
37
+ """
38
+
39
+ def __init__(self):
40
+ """Initializes the monitor and starts background threads."""
41
+ self._igpu_usage = 0.0
42
+ self._igpu_last_updated = 0.0
43
+ self._igpu_lock = threading.Lock()
44
+ self._stop_event = threading.Event()
45
+ self._cpu_count = psutil.cpu_count(logical=True)
46
+
47
+ log_path = '.'
48
+ if os.path.isdir(log_path) is not True:
49
+ print(f"{log_path} is invalid!")
50
+ exit(1)
51
+ self.time_0 = datetime.now()
52
+ log_ts = str(log_path) + f"/{self.time_0.isoformat()}"
53
+
54
+ self.log_file_name = f"{log_ts}_perf_monitor.log"
55
+
56
+ self._previous_logged_top_pids = []
57
+
58
+ self._setup_logging()
59
+
60
+ # daemon=True ensures threads will exit when the main program does
61
+ self._igpu_thread = threading.Thread(target=self._igpu_monitor_thread, daemon=True)
62
+ self._igpu_thread.start()
63
+
64
+ self._keyboard_thread = threading.Thread(target=self._keyboard_listener_thread, daemon=True)
65
+ self._keyboard_thread.start()
66
+
67
+ def _setup_logging(self):
68
+ """Sets up the CSV logger."""
69
+ self._logger = logging.getLogger('SystemMonitorLogger')
70
+ self._logger.setLevel(logging.INFO)
71
+ self._logger.propagate = False
72
+
73
+ handler = logging.FileHandler(self.log_file_name, mode='w')
74
+ self._logger.addHandler(handler)
75
+
76
+
77
+ def stop(self):
78
+ """Signals all monitoring threads to stop."""
79
+ self._stop_event.set()
80
+
81
+ def _keyboard_listener_thread(self):
82
+ """
83
+ A background thread that listens for the 'q' key to stop the monitor.
84
+ """
85
+ if os.name != 'posix':
86
+ return
87
+
88
+ fd = sys.stdin.fileno()
89
+ old_settings = termios.tcgetattr(fd)
90
+ try:
91
+ tty.setcbreak(sys.stdin.fileno())
92
+ while not self._stop_event.is_set():
93
+ if select.select([sys.stdin], [], [], 0.1)[0]:
94
+ char = sys.stdin.read(1)
95
+ if char.lower() == 'q':
96
+ self.stop()
97
+ break
98
+ finally:
99
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
100
+
101
+
102
+ def _igpu_monitor_thread(self):
103
+ """
104
+ The background thread function that runs `intel_gpu_top` continuously
105
+ and updates the iGPU usage value by parsing the JSON stream.
106
+ """
107
+ process = None
108
+ while not self._stop_event.is_set():
109
+ try:
110
+ command = ["intel_gpu_top", "-J", "-s", "1000"]
111
+ process = subprocess.Popen(
112
+ command,
113
+ stdout=subprocess.PIPE,
114
+ stderr=subprocess.DEVNULL,
115
+ text=True,
116
+ stdin=subprocess.DEVNULL
117
+ )
118
+
119
+ json_buffer = ""
120
+ brace_count = 0
121
+
122
+ for char in iter(lambda: process.stdout.read(1), ''):
123
+ if self._stop_event.is_set():
124
+ break
125
+
126
+ if char == '{':
127
+ if brace_count == 0:
128
+ json_buffer = ""
129
+ brace_count += 1
130
+
131
+ if brace_count > 0:
132
+ json_buffer += char
133
+
134
+ if char == '}':
135
+ brace_count -= 1
136
+
137
+ if brace_count == 0 and json_buffer:
138
+ try:
139
+ data = json.loads(json_buffer)
140
+ if isinstance(data, list) and data:
141
+ data = data[0]
142
+
143
+ engines = data.get("engines")
144
+ if isinstance(engines, dict):
145
+ render_engine = engines.get("Render/3D")
146
+ if isinstance(render_engine, dict):
147
+ usage = float(render_engine.get("busy", 0.0))
148
+ with self._igpu_lock:
149
+ self._igpu_usage = usage
150
+ self._igpu_last_updated = time.monotonic()
151
+ except json.JSONDecodeError:
152
+ pass
153
+ finally:
154
+ json_buffer = ""
155
+
156
+ process.wait()
157
+ if not self._stop_event.is_set():
158
+ time.sleep(1)
159
+
160
+ except (FileNotFoundError, ValueError):
161
+ break
162
+ finally:
163
+ if process:
164
+ try:
165
+ process.kill()
166
+ process.wait()
167
+ except OSError:
168
+ pass
169
+
170
+ def get_cpu_usage(self, interval: float = 1) -> float:
171
+ """Returns the system-wide CPU utilization as a percentage."""
172
+ return psutil.cpu_percent(interval=interval)
173
+
174
+ def get_cpu_count(self) -> int:
175
+ """Returns the number of logical CPU cores."""
176
+ return self._cpu_count
177
+
178
+ def get_igpu_usage(self) -> Optional[float]:
179
+ """
180
+ Returns the latest iGPU usage percentage from the background thread.
181
+ If the data is stale (older than 1.5s), it returns 0.0.
182
+ """
183
+ with self._igpu_lock:
184
+ if time.monotonic() - self._igpu_last_updated > 1.5:
185
+ return 0.0
186
+ return self._igpu_usage
187
+
188
+ def get_gpu_usage(self) -> Optional[float]:
189
+ """
190
+ Gets NVIDIA GPU usage by running the `nvidia-smi` command.
191
+ """
192
+ try:
193
+ command = ["nvidia-smi", "--query-gpu=utilization.gpu", "--format=csv,noheader,nounits"]
194
+ result = subprocess.run(command, capture_output=True, text=True, check=True)
195
+ return float(result.stdout.strip())
196
+ except (FileNotFoundError, subprocess.CalledProcessError, ValueError):
197
+ return None
198
+
199
+ def get_memory_usage(self) -> Dict[str, float]:
200
+ """
201
+ Returns a dictionary with detailed memory usage statistics in GB.
202
+ """
203
+ mem = psutil.virtual_memory()
204
+ mem_total_gb = mem.total / (1024**3)
205
+ mem_available_gb = mem.available / (1024**3)
206
+
207
+ return {
208
+ "total_gb": mem_total_gb,
209
+ "available_gb": mem_available_gb,
210
+ "used_gb": mem_total_gb - mem_available_gb,
211
+ "percent_used": mem.percent,
212
+ "cache_buffers_gb": (mem.buffers + mem.cached) / (1024**3)
213
+ }
214
+
215
+ def get_storage_usage(self) -> Optional[Dict[str, float]]:
216
+ """
217
+ Returns a dictionary with usage statistics for the root filesystem '/'.
218
+ """
219
+ try:
220
+ usage = psutil.disk_usage('/')
221
+ return {
222
+ "total_gb": usage.total / (1024**3),
223
+ "used_gb": usage.used / (1024**3),
224
+ "free_gb": usage.free / (1024**3),
225
+ "percent_used": usage.percent,
226
+ }
227
+ except (FileNotFoundError, Exception):
228
+ return None
229
+
230
+
231
+ def get_load_average(self) -> Optional[Tuple[float, float, float]]:
232
+ """Returns the system load average over 1, 5, and 15 minutes."""
233
+ try:
234
+ return psutil.getloadavg()
235
+ except (AttributeError, NotImplementedError):
236
+ return None
237
+
238
+ def get_temperatures(self) -> Dict[str, Dict[str, Optional[float]]]:
239
+ """
240
+ Runs the 'sensors' command to get key hardware temperatures and their
241
+ high/critical thresholds. Returns a dictionary of dictionaries.
242
+ """
243
+ temps = {
244
+ "CPU": {"current": None, "high": None, "crit": None},
245
+ "GPU": {"current": None, "high": None, "crit": None},
246
+ "Board": {"current": None, "high": None, "crit": None},
247
+ "NVMe": {"current": None, "high": None, "crit": None},
248
+ }
249
+ try:
250
+ result = subprocess.run(['sensors'], capture_output=True, text=True, check=False)
251
+ if result.returncode != 0:
252
+ return temps
253
+
254
+ current_module = ""
255
+ for line in result.stdout.splitlines():
256
+ if not line.strip() or ":" not in line:
257
+ if line.strip():
258
+ current_module = line.strip()
259
+ continue
260
+
261
+ temp_match = re.search(r'\+(\d+\.\d+)°C', line)
262
+ high_match = re.search(r'high\s*=\s*\+(\d+\.\d+)°C', line)
263
+ crit_match = re.search(r'crit\s*=\s*\+(\d+\.\d+)°C', line)
264
+
265
+ current_temp = float(temp_match.group(1)) if temp_match else None
266
+ high_temp = float(high_match.group(1)) if high_match else None
267
+ crit_temp = float(crit_match.group(1)) if crit_match else None
268
+
269
+ if current_temp is None:
270
+ continue
271
+
272
+ if 'Package id 0:' in line and 'coretemp' in current_module:
273
+ temps["CPU"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
274
+ elif 'GPU:' in line and 'thinkpad' in current_module:
275
+ temps["GPU"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
276
+ elif 'Composite:' in line and 'nvme' in current_module:
277
+ temps["NVMe"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
278
+ elif 'temp1:' in line and 'acpitz' in current_module:
279
+ temps["Board"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
280
+
281
+ return temps
282
+ except (FileNotFoundError, Exception):
283
+ return temps
284
+
285
+ def get_top_memory_processes(self) -> List[Dict]:
286
+ """
287
+ Gets a list of the top 5 memory-consuming processes, sorted by
288
+ Resident Set Size (RSS). It also includes Unique Set Size (USS)
289
+ if it's accessible.
290
+ """
291
+ all_processes = []
292
+ # Request both memory_info (for RSS) and memory_full_info (for USS)
293
+ for p in psutil.process_iter(['pid', 'name', 'memory_info', 'memory_full_info', 'cmdline']):
294
+ try:
295
+ # --- Get RSS (Reliable) ---
296
+ mem_info = p.info['memory_info']
297
+ if not mem_info or not mem_info.rss:
298
+ continue
299
+ rss_mb = mem_info.rss / (1024**2)
300
+
301
+ # --- Get USS (May fail due to permissions) ---
302
+ uss_mb = None
303
+ try:
304
+ # memory_full_info() is the part that requires higher privileges
305
+ if hasattr(p.info['memory_full_info'], 'uss'):
306
+ uss_mb = p.info['memory_full_info'].uss / (1024**2)
307
+ except (psutil.AccessDenied, AttributeError):
308
+ # Silently ignore if we can't get USS, uss_mb will remain None
309
+ pass
310
+
311
+ full_cmd = ' '.join(p.info['cmdline']) if p.info['cmdline'] else p.info['name']
312
+
313
+ if 'perf_monitor.py' in full_cmd or sys.argv[0] in full_cmd:
314
+ continue
315
+
316
+ all_processes.append({
317
+ 'pid': p.info['pid'],
318
+ 'full_cmd': full_cmd,
319
+ 'rss_mb': rss_mb, # Changed from memory_mb for clarity
320
+ 'uss_mb': uss_mb
321
+ })
322
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
323
+ # This outer block catches errors if the process disappears
324
+ # or if we can't even get basic memory_info.
325
+ pass
326
+
327
+ # Sort by RSS, as it's the most reliable indicator of memory pressure
328
+ return sorted(all_processes, key=lambda x: x['rss_mb'], reverse=True)[:5]
329
+
330
+ def log_top_processes(logger: logging.Logger, prefix: str, processes: List[Dict]):
331
+ """Helper function to log the top 5 processes with RSS and USS."""
332
+ if processes:
333
+ logger.info(f"{prefix}: Top 5 memory processes (Sorted by RSS):")
334
+ for i, proc in enumerate(processes):
335
+ rss_mb = proc['rss_mb']
336
+ uss_mb = proc.get('uss_mb') # Use .get() for safety
337
+
338
+ uss_str = f"{uss_mb:>7.2f} MB" if uss_mb is not None else " N/A "
339
+
340
+ log_proc_entry = (
341
+ f" {i+1}. PID: {proc['pid']:<8} | "
342
+ f"RSS: {rss_mb:>7.2f} MB | "
343
+ f"USS: {uss_str} | "
344
+ f"{proc['full_cmd']}"
345
+ )
346
+ logger.info(log_proc_entry)
347
+
348
+
349
+ @command("perf-monitor")
350
+ def perf_monitor(is_command=True):
351
+ """Main function to run the live performance monitor as a standalone script."""
352
+ parser = argparse.ArgumentParser(description="A system resource monitor.")
353
+ parser.add_argument(
354
+ "--memory",
355
+ default=True,
356
+ action="store_true",
357
+ help="Always display the top memory-consuming processes."
358
+ )
359
+ args = subcommand_parse_args(parser, is_command)
360
+
361
+ monitor = PerfMonitor()
362
+
363
+ def clear_screen():
364
+ os.system('cls' if os.name == 'nt' else 'clear')
365
+
366
+ start_time = time.monotonic()
367
+
368
+ log_top_processes(monitor._logger, "[START]", monitor.get_top_memory_processes())
369
+
370
+ try:
371
+ while not monitor._stop_event.is_set():
372
+ cpu_percent = monitor.get_cpu_usage(interval=0.1)
373
+ cpu_count = monitor.get_cpu_count()
374
+ igpu_percent = monitor.get_igpu_usage()
375
+ gpu_percent = monitor.get_gpu_usage()
376
+ mem_stats = monitor.get_memory_usage()
377
+ storage_stats = monitor.get_storage_usage()
378
+ load_avg = monitor.get_load_average()
379
+ temps = monitor.get_temperatures()
380
+
381
+ is_oom = mem_stats["percent_used"] > HIGH_MEMORY_THRESHOLD_PERCENT
382
+
383
+ ts = time.strftime('%Y-%m-%d %H:%M:%S')
384
+
385
+ cpu_log = f"CPU {cpu_percent:.2f}%"
386
+ load_log = f"{load_avg[0]:.2f}/{cpu_count} Cores" if load_avg else "N/A"
387
+ cpu_temp_log = f"{temps['CPU']['current']:.1f}°C" if temps.get('CPU', {}).get('current') is not None else "N/A"
388
+ mem_log = f"Mem {mem_stats['percent_used']:.2f}%"
389
+ mem_used_log = f"{mem_stats['used_gb']:.2f}/{mem_stats['total_gb']:.2f}G"
390
+ storage_log = f"Storage {storage_stats['percent_used']:.2f}%" if storage_stats else "N/A"
391
+ igpu_log = f"iGPU {igpu_percent:.2f}%" if igpu_percent is not None else "iGPU N/A"
392
+ gpu_log = f"GPU {gpu_percent:.2f}%" if gpu_percent is not None else "GPU N/A"
393
+ gpu_temp_log = f"{temps['GPU']['current']:.1f}C" if temps.get('GPU', {}).get('current') is not None else "GPU Temp: N/A"
394
+
395
+
396
+ board_temp_log = f"{temps['Board']['current']:.1f}°C" if temps.get('Board', {}).get('current') is not None else ""
397
+
398
+ log_entry = (
399
+ f"{ts}] {cpu_log} {load_log} {cpu_temp_log} | {mem_log} {mem_used_log} {board_temp_log} | {storage_log} | "
400
+ f"{igpu_log} | {gpu_log} {gpu_temp_log}"
401
+ )
402
+ monitor._logger.info(log_entry.strip())
403
+
404
+ if args.memory or is_oom:
405
+ top_memory_procs = monitor.get_top_memory_processes()
406
+
407
+ if is_oom:
408
+ current_pids = [p['pid'] for p in top_memory_procs]
409
+ if current_pids != monitor._previous_logged_top_pids:
410
+ log_top_processes(monitor._logger, f"CRITICAL MEMORY {HIGH_MEMORY_THRESHOLD_PERCENT}% USED", top_memory_procs)
411
+ monitor._previous_logged_top_pids = current_pids
412
+ else:
413
+ monitor._previous_logged_top_pids = []
414
+
415
+ clear_screen()
416
+
417
+ uptime_seconds = int(time.monotonic() - start_time)
418
+ uptime_str = time.strftime('%H:%M:%S', time.gmtime(uptime_seconds))
419
+ current_time_str = time.strftime('%Y-%m-%d %H:%M:%S')
420
+ print(f" {current_time_str} Uptime {uptime_str}")
421
+
422
+ cpu_bar = '█' * int(40 * cpu_percent / 100) + '-' * (40 - int(40 * cpu_percent / 100))
423
+ print(f"CPU Usage : |{cpu_bar}| {cpu_percent:.2f}%")
424
+
425
+ load_str = f"{load_avg[0]:.2f}, {load_avg[1]:.2f}, {load_avg[2]:.2f} / {cpu_count} Cores" if load_avg else "N/A"
426
+ print(f" Load Avg {load_str} (1, 5, 15 min)")
427
+
428
+ mem_bar = '█' * int(40 * mem_stats["percent_used"] / 100) + '-' * (40 - int(40 * mem_stats["percent_used"] / 100))
429
+ print(f"Mem (Used) : |{mem_bar}| {mem_stats['percent_used']:.2f}%")
430
+
431
+ # Cache/Buff: {mem_stats['cache_buffers_gb']:.2f}G | Available: {mem_stats['available_gb']:.2f}G
432
+ print(f" Used: {mem_stats['used_gb']:.2f}G / Total: {mem_stats['total_gb']:.2f}G")
433
+
434
+ if storage_stats:
435
+ storage_bar = '█' * int(40 * storage_stats['percent_used'] / 100) + '-' * (40 - int(40 * storage_stats['percent_used'] / 100))
436
+ print(f"Storage / : |{storage_bar}| {storage_stats['percent_used']:.2f}%")
437
+ print(f" Used: {storage_stats['used_gb']:.2f}G / Total: {storage_stats['total_gb']:.2f}G")
438
+
439
+ if igpu_percent is not None:
440
+ igpu_bar = '█' * int(40 * igpu_percent / 100) + '-' * (40 - int(40 * igpu_percent / 100))
441
+ print(f"iGPU Usage : |{igpu_bar}| {igpu_percent:.2f}%")
442
+
443
+ if gpu_percent is not None:
444
+ gpu_bar = '█' * int(40 * gpu_percent / 100) + '-' * (40 - int(40 * gpu_percent / 100))
445
+ print(f"GPU Usage : |{gpu_bar}| {gpu_percent:.2f}%")
446
+
447
+ print()
448
+
449
+ headers = ["CPU", "GPU", "Board (ACPI)", "NVMe"]
450
+ keys = ["CPU", "GPU", "Board", "NVMe"]
451
+ values = []
452
+
453
+ for key in keys:
454
+ temp_data = temps.get(key)
455
+ value_str = "N/A"
456
+ if temp_data and temp_data['current'] is not None:
457
+ value_str = f"{temp_data['current']:.1f}°C"
458
+ details = []
459
+ if temp_data['high'] is not None:
460
+ details.append(f"h={temp_data['high']:.1f}")
461
+ if temp_data['crit'] is not None:
462
+ details.append(f"c={temp_data['crit']:.1f}")
463
+ if details:
464
+ value_str += f" ({','.join(details)})"
465
+ values.append(value_str)
466
+
467
+ widths = [max(len(h), len(v)) for h, v in zip(headers, values)]
468
+
469
+ header_line_parts = [f"{h:<{w}}" for h, w in zip(headers, widths)]
470
+ value_line_parts = [f"{v:<{w}}" for v, w in zip(values, widths)]
471
+
472
+ print(" | ".join(header_line_parts))
473
+ print(" | ".join(value_line_parts))
474
+
475
+ # Also added spacing to prevent flickering
476
+ process_section_header = "Top 5 Memory Processes (Sorted by RSS):"
477
+ process_lines_to_print = []
478
+
479
+ if args.memory or is_oom:
480
+ # Prepend the warning banner if needed
481
+ if is_oom:
482
+ process_section_header = f"CRITICAL MEMORY {HIGH_MEMORY_THRESHOLD_PERCENT}% USED: " + process_section_header
483
+
484
+ process_lines_to_print.append(process_section_header.strip())
485
+ process_lines_to_print.append(f" {'PID':<8} | {'RSS':>12} | {'USS':>12} | Command")
486
+
487
+ if top_memory_procs:
488
+ for i, proc in enumerate(top_memory_procs):
489
+ rss_str = f"{proc['rss_mb']:>7.2f} MB"
490
+
491
+ uss_mb = proc.get('uss_mb')
492
+ uss_str = f"{uss_mb:>7.2f} MB" if uss_mb is not None else "N/A"
493
+
494
+ cmd_str = (proc['full_cmd'][:55] + '...') if len(proc['full_cmd']) > 58 else proc['full_cmd']
495
+
496
+ process_lines_to_print.append(f"{i+1}. {proc['pid']:<8} | {rss_str:>12} | {uss_str:>12} | {cmd_str}")
497
+ else:
498
+ process_lines_to_print.append("No running processes found.")
499
+
500
+ if process_lines_to_print:
501
+ print("\n" + "\n".join(process_lines_to_print))
502
+
503
+ print("\n sudo is required for iGPU usage access. Press 'q' to exit")
504
+
505
+ time.sleep(1)
506
+
507
+ except (ImportError, NameError):
508
+ print("Live keyboard monitoring not supported on this OS. Use Ctrl+C to exit.")
509
+ while True:
510
+ try:
511
+ time.sleep(1)
512
+ except KeyboardInterrupt:
513
+ break
514
+
515
+ except KeyboardInterrupt:
516
+ print("\nExiting monitor gracefully...")
517
+ finally:
518
+ monitor.stop()
519
+ log_top_processes(monitor._logger, "[STOP]", monitor.get_top_memory_processes())
520
+ print(f"\nLog file '{monitor.log_file_name}' has been created.")
521
+
522
+ if __name__ == "__main__":
523
+ by_name["perf-monitor"](False)
524
+
@@ -7,10 +7,11 @@ en:
7
7
  brainframe-sys-tools <command> [<args>]
8
8
 
9
9
  commands:
10
- fps_monitor
11
- service_monitor
12
- sys_info
13
- ssh_tunnel
10
+ fps-monitor
11
+ perf-monitor
12
+ service-monitor
13
+ sys-info
14
+ ssh-tunnel
14
15
 
15
16
  Examples:
16
17
  brainframe-sys-tools fps_monitor
@@ -1,7 +1,8 @@
1
1
  [tool.poetry]
2
2
  name = "brainframe-sys-tools"
3
- version = "0.5.3"
3
+ version = "0.5.5"
4
4
  description = "This is the package including tools for BrainFrame developers to monitor and debug the system."
5
+ readme = "README.md"
5
6
  authors = ["Stephen Li <stephen@aotu.ai>"]
6
7
  license = "BSD License"
7
8
  classifiers = [
@@ -15,8 +16,8 @@ python = "^3.9,<4.0"
15
16
  python_i18n = "^0.3.9"
16
17
  PyYAML = "^6.0.2"
17
18
  requests = "^2.32.3"
18
- brainframe_apps = "^0.5.3"
19
- brainframe-api = "^0.30.3"
19
+ brainframe_apps = "^0.5.4"
20
+ brainframe-api = "^0.30.4"
20
21
  apscheduler = "^3.10.4"
21
22
  psutil = "^5.8.0"
22
23
  tabulate = "^0.8.9"