brainframe-sys-tools 0.5.4__tar.gz → 0.5.6__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.
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/PKG-INFO +40 -2
- brainframe_sys_tools-0.5.6/README.md +36 -0
- brainframe_sys_tools-0.5.6/brainframe_sys_tools/.python-version +1 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/__init__.py +7 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/bf_info.py +10 -8
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/bf_service_monitor.py +12 -8
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/bf_ssh_tunnel.py +10 -8
- brainframe_sys_tools-0.5.6/brainframe_sys_tools/brainframe_monitor/__pycache__/benchmarker.cpython-312.pyc +0 -0
- brainframe_sys_tools-0.5.6/brainframe_sys_tools/brainframe_monitor/__pycache__/brainframe_monitor.cpython-312.pyc +0 -0
- brainframe_sys_tools-0.5.6/brainframe_sys_tools/brainframe_monitor/__pycache__/fake_screen.cpython-312.pyc +0 -0
- brainframe_sys_tools-0.5.6/brainframe_sys_tools/brainframe_monitor/__pycache__/report.cpython-312.pyc +0 -0
- brainframe_sys_tools-0.5.6/brainframe_sys_tools/brainframe_monitor/__pycache__/system_monitor.cpython-312.pyc +0 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/brainframe_monitor/benchmarker.py +7 -2
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/brainframe_monitor/brainframe_monitor.py +27 -18
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/cli.py +5 -1
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/command_utils.py +6 -2
- brainframe_sys_tools-0.5.6/brainframe_sys_tools/perf_monitor.py +725 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/translations/portal.en.yml +5 -4
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/pyproject.toml +2 -1
- brainframe_sys_tools-0.5.4/brainframe_sys_tools/brainframe_monitor/__pycache__/benchmarker.cpython-38.pyc +0 -0
- brainframe_sys_tools-0.5.4/brainframe_sys_tools/brainframe_monitor/__pycache__/curses_utils.cpython-38.pyc +0 -0
- brainframe_sys_tools-0.5.4/brainframe_sys_tools/brainframe_monitor/__pycache__/fake_screen.cpython-38.pyc +0 -0
- brainframe_sys_tools-0.5.4/brainframe_sys_tools/brainframe_monitor/__pycache__/report.cpython-38.pyc +0 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/COPYING +0 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/brainframe_monitor/curses_utils.py +0 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/brainframe_monitor/fake_screen.py +0 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/brainframe_monitor/report.py +0 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/check_memory.py +0 -0
- {brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/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
|
+
Version: 0.5.6
|
|
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,7 +13,6 @@ 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
18
|
Requires-Dist: brainframe-api (>=0.30.4,<0.31.0)
|
|
@@ -22,3 +21,42 @@ 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
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.9
|
|
@@ -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
|
-
|
|
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
|
|
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("
|
|
146
|
-
def sys_info():
|
|
147
|
-
|
|
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["
|
|
157
|
+
by_name["sys-info"](False)
|
{brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/bf_service_monitor.py
RENAMED
|
@@ -12,8 +12,12 @@ from typing import Callable
|
|
|
12
12
|
|
|
13
13
|
from brainframe.api import BrainFrameAPI
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
from
|
|
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
|
-
|
|
297
|
-
return args
|
|
300
|
+
return parser
|
|
298
301
|
|
|
299
302
|
|
|
300
|
-
@command("
|
|
301
|
-
def service_monitor():
|
|
302
|
-
|
|
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["
|
|
347
|
+
by_name["service-monitor"](False)
|
{brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/bf_ssh_tunnel.py
RENAMED
|
@@ -5,7 +5,10 @@
|
|
|
5
5
|
import subprocess
|
|
6
6
|
from argparse import ArgumentParser
|
|
7
7
|
|
|
8
|
-
|
|
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
|
-
|
|
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("
|
|
78
|
-
def ssh_tunnel():
|
|
79
|
-
|
|
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["
|
|
106
|
+
by_name["ssh-tunnel"](False)
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -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
|
-
|
|
13
|
-
from
|
|
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="
|
|
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
|
-
|
|
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["
|
|
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
|
-
|
|
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=""):
|
{brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/command_utils.py
RENAMED
|
@@ -14,8 +14,12 @@ def command(name):
|
|
|
14
14
|
return wrapper
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
def subcommand_parse_args(parser: ArgumentParser):
|
|
18
|
-
|
|
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,725 @@
|
|
|
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
|
+
try:
|
|
30
|
+
import docker
|
|
31
|
+
from docker.errors import DockerException
|
|
32
|
+
import requests
|
|
33
|
+
except ImportError:
|
|
34
|
+
docker = None
|
|
35
|
+
|
|
36
|
+
HIGH_MEMORY_THRESHOLD_PERCENT = 95.0
|
|
37
|
+
|
|
38
|
+
class PerfMonitor:
|
|
39
|
+
"""
|
|
40
|
+
A modular class to fetch system resource usage statistics. It runs
|
|
41
|
+
background threads for continuous iGPU and keyboard monitoring.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(self):
|
|
45
|
+
"""Initializes the monitor and starts background threads."""
|
|
46
|
+
self._igpu_usage = 0.0
|
|
47
|
+
self._igpu_last_updated = 0.0
|
|
48
|
+
self._igpu_lock = threading.Lock()
|
|
49
|
+
self._stop_event = threading.Event()
|
|
50
|
+
self._cpu_count = psutil.cpu_count(logical=True)
|
|
51
|
+
|
|
52
|
+
log_path = '.'
|
|
53
|
+
if os.path.isdir(log_path) is not True:
|
|
54
|
+
print(f"{log_path} is invalid!")
|
|
55
|
+
exit(1)
|
|
56
|
+
self.time_0 = datetime.now()
|
|
57
|
+
log_ts = str(log_path) + f"/{self.time_0.isoformat()}"
|
|
58
|
+
|
|
59
|
+
self.log_file_name = f"{log_ts}_perf_monitor.log"
|
|
60
|
+
|
|
61
|
+
self._previous_logged_top_pids = []
|
|
62
|
+
|
|
63
|
+
self._setup_logging()
|
|
64
|
+
|
|
65
|
+
# daemon=True ensures threads will exit when the main program does
|
|
66
|
+
self._igpu_thread = threading.Thread(target=self._igpu_monitor_thread, daemon=True)
|
|
67
|
+
self._igpu_thread.start()
|
|
68
|
+
|
|
69
|
+
self._keyboard_thread = threading.Thread(target=self._keyboard_listener_thread, daemon=True)
|
|
70
|
+
self._keyboard_thread.start()
|
|
71
|
+
|
|
72
|
+
def _setup_logging(self):
|
|
73
|
+
"""Sets up the CSV logger."""
|
|
74
|
+
self._logger = logging.getLogger('SystemMonitorLogger')
|
|
75
|
+
self._logger.setLevel(logging.INFO)
|
|
76
|
+
self._logger.propagate = False
|
|
77
|
+
|
|
78
|
+
handler = logging.FileHandler(self.log_file_name, mode='w')
|
|
79
|
+
self._logger.addHandler(handler)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def stop(self):
|
|
83
|
+
"""Signals all monitoring threads to stop."""
|
|
84
|
+
self._stop_event.set()
|
|
85
|
+
|
|
86
|
+
def _keyboard_listener_thread(self):
|
|
87
|
+
"""
|
|
88
|
+
A background thread that listens for the 'q' key to stop the monitor.
|
|
89
|
+
"""
|
|
90
|
+
if os.name != 'posix':
|
|
91
|
+
return
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
fd = sys.stdin.fileno()
|
|
95
|
+
old_settings = termios.tcgetattr(fd)
|
|
96
|
+
try:
|
|
97
|
+
tty.setcbreak(sys.stdin.fileno())
|
|
98
|
+
while not self._stop_event.is_set():
|
|
99
|
+
if select.select([sys.stdin], [], [], 0.1)[0]:
|
|
100
|
+
char = sys.stdin.read(1)
|
|
101
|
+
if char.lower() == 'q':
|
|
102
|
+
self.stop()
|
|
103
|
+
break
|
|
104
|
+
finally:
|
|
105
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
|
|
106
|
+
except (termios.error, OSError):
|
|
107
|
+
# This will happen when run with sudo, as there is no interactive tty.
|
|
108
|
+
# The thread will simply exit, and the user must use Ctrl+C.
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _igpu_monitor_thread(self):
|
|
113
|
+
"""
|
|
114
|
+
The background thread function that runs `intel_gpu_top` continuously
|
|
115
|
+
and updates the iGPU usage value by parsing the JSON stream.
|
|
116
|
+
"""
|
|
117
|
+
process = None
|
|
118
|
+
while not self._stop_event.is_set():
|
|
119
|
+
try:
|
|
120
|
+
command = ["intel_gpu_top", "-J", "-s", "1000"]
|
|
121
|
+
process = subprocess.Popen(
|
|
122
|
+
command,
|
|
123
|
+
stdout=subprocess.PIPE,
|
|
124
|
+
stderr=subprocess.DEVNULL,
|
|
125
|
+
text=True,
|
|
126
|
+
stdin=subprocess.DEVNULL
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
json_buffer = ""
|
|
130
|
+
brace_count = 0
|
|
131
|
+
|
|
132
|
+
for char in iter(lambda: process.stdout.read(1), ''):
|
|
133
|
+
if self._stop_event.is_set():
|
|
134
|
+
break
|
|
135
|
+
|
|
136
|
+
if char == '{':
|
|
137
|
+
if brace_count == 0:
|
|
138
|
+
json_buffer = ""
|
|
139
|
+
brace_count += 1
|
|
140
|
+
|
|
141
|
+
if brace_count > 0:
|
|
142
|
+
json_buffer += char
|
|
143
|
+
|
|
144
|
+
if char == '}':
|
|
145
|
+
brace_count -= 1
|
|
146
|
+
|
|
147
|
+
if brace_count == 0 and json_buffer:
|
|
148
|
+
try:
|
|
149
|
+
data = json.loads(json_buffer)
|
|
150
|
+
if isinstance(data, list) and data:
|
|
151
|
+
data = data[0]
|
|
152
|
+
|
|
153
|
+
engines = data.get("engines")
|
|
154
|
+
if isinstance(engines, dict):
|
|
155
|
+
render_engine = engines.get("Render/3D")
|
|
156
|
+
if isinstance(render_engine, dict):
|
|
157
|
+
usage = float(render_engine.get("busy", 0.0))
|
|
158
|
+
with self._igpu_lock:
|
|
159
|
+
self._igpu_usage = usage
|
|
160
|
+
self._igpu_last_updated = time.monotonic()
|
|
161
|
+
except json.JSONDecodeError:
|
|
162
|
+
pass
|
|
163
|
+
finally:
|
|
164
|
+
json_buffer = ""
|
|
165
|
+
|
|
166
|
+
process.wait()
|
|
167
|
+
if not self._stop_event.is_set():
|
|
168
|
+
time.sleep(1)
|
|
169
|
+
|
|
170
|
+
except (FileNotFoundError, ValueError):
|
|
171
|
+
break
|
|
172
|
+
finally:
|
|
173
|
+
if process:
|
|
174
|
+
try:
|
|
175
|
+
process.kill()
|
|
176
|
+
process.wait()
|
|
177
|
+
except OSError:
|
|
178
|
+
pass
|
|
179
|
+
|
|
180
|
+
def get_cpu_usage(self, interval: float = 1) -> float:
|
|
181
|
+
"""Returns the system-wide CPU utilization as a percentage."""
|
|
182
|
+
return psutil.cpu_percent(interval=interval)
|
|
183
|
+
|
|
184
|
+
def get_cpu_count(self) -> int:
|
|
185
|
+
"""Returns the number of logical CPU cores."""
|
|
186
|
+
return self._cpu_count
|
|
187
|
+
|
|
188
|
+
def get_igpu_usage(self) -> Optional[float]:
|
|
189
|
+
"""
|
|
190
|
+
Returns the latest iGPU usage percentage from the background thread.
|
|
191
|
+
If the data is stale (older than 1.5s), it returns 0.0.
|
|
192
|
+
"""
|
|
193
|
+
with self._igpu_lock:
|
|
194
|
+
if time.monotonic() - self._igpu_last_updated > 1.5:
|
|
195
|
+
return 0.0
|
|
196
|
+
return self._igpu_usage
|
|
197
|
+
|
|
198
|
+
def get_gpu_usage(self) -> Optional[float]:
|
|
199
|
+
"""
|
|
200
|
+
Gets NVIDIA GPU usage by running the `nvidia-smi` command.
|
|
201
|
+
"""
|
|
202
|
+
try:
|
|
203
|
+
command = ["nvidia-smi", "--query-gpu=utilization.gpu", "--format=csv,noheader,nounits"]
|
|
204
|
+
result = subprocess.run(command, capture_output=True, text=True, check=True)
|
|
205
|
+
return float(result.stdout.strip())
|
|
206
|
+
except (FileNotFoundError, subprocess.CalledProcessError, ValueError):
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
def get_memory_usage(self) -> Dict[str, float]:
|
|
210
|
+
"""
|
|
211
|
+
Returns a dictionary with detailed memory usage statistics in GB.
|
|
212
|
+
"""
|
|
213
|
+
mem = psutil.virtual_memory()
|
|
214
|
+
mem_total_gb = mem.total / (1024**3)
|
|
215
|
+
mem_available_gb = mem.available / (1024**3)
|
|
216
|
+
|
|
217
|
+
return {
|
|
218
|
+
"total_gb": mem_total_gb,
|
|
219
|
+
"available_gb": mem_available_gb,
|
|
220
|
+
"used_gb": mem_total_gb - mem_available_gb,
|
|
221
|
+
"percent_used": mem.percent,
|
|
222
|
+
"cache_buffers_gb": (mem.buffers + mem.cached) / (1024**3)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
def get_storage_usage(self) -> Optional[Dict[str, float]]:
|
|
226
|
+
"""
|
|
227
|
+
Returns a dictionary with usage statistics for the root filesystem '/'.
|
|
228
|
+
"""
|
|
229
|
+
try:
|
|
230
|
+
usage = psutil.disk_usage('/')
|
|
231
|
+
return {
|
|
232
|
+
"total_gb": usage.total / (1024**3),
|
|
233
|
+
"used_gb": usage.used / (1024**3),
|
|
234
|
+
"free_gb": usage.free / (1024**3),
|
|
235
|
+
"percent_used": usage.percent,
|
|
236
|
+
}
|
|
237
|
+
except (FileNotFoundError, Exception):
|
|
238
|
+
return None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def get_load_average(self) -> Optional[Tuple[float, float, float]]:
|
|
242
|
+
"""Returns the system load average over 1, 5, and 15 minutes."""
|
|
243
|
+
try:
|
|
244
|
+
return psutil.getloadavg()
|
|
245
|
+
except (AttributeError, NotImplementedError):
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
def get_temperatures(self) -> Dict[str, Dict[str, Optional[float]]]:
|
|
249
|
+
"""
|
|
250
|
+
Runs the 'sensors' command to get key hardware temperatures and their
|
|
251
|
+
high/critical thresholds. Returns a dictionary of dictionaries.
|
|
252
|
+
"""
|
|
253
|
+
temps = {
|
|
254
|
+
"CPU": {"current": None, "high": None, "crit": None},
|
|
255
|
+
"GPU": {"current": None, "high": None, "crit": None},
|
|
256
|
+
"Board": {"current": None, "high": None, "crit": None},
|
|
257
|
+
"NVMe": {"current": None, "high": None, "crit": None},
|
|
258
|
+
}
|
|
259
|
+
try:
|
|
260
|
+
result = subprocess.run(['sensors'], capture_output=True, text=True, check=False)
|
|
261
|
+
if result.returncode != 0:
|
|
262
|
+
return temps
|
|
263
|
+
|
|
264
|
+
current_module = ""
|
|
265
|
+
for line in result.stdout.splitlines():
|
|
266
|
+
if not line.strip() or ":" not in line:
|
|
267
|
+
if line.strip():
|
|
268
|
+
current_module = line.strip()
|
|
269
|
+
continue
|
|
270
|
+
|
|
271
|
+
temp_match = re.search(r'\+(\d+\.\d+)°C', line)
|
|
272
|
+
high_match = re.search(r'high\s*=\s*\+(\d+\.\d+)°C', line)
|
|
273
|
+
crit_match = re.search(r'crit\s*=\s*\+(\d+\.\d+)°C', line)
|
|
274
|
+
|
|
275
|
+
current_temp = float(temp_match.group(1)) if temp_match else None
|
|
276
|
+
high_temp = float(high_match.group(1)) if high_match else None
|
|
277
|
+
crit_temp = float(crit_match.group(1)) if crit_match else None
|
|
278
|
+
|
|
279
|
+
if current_temp is None:
|
|
280
|
+
continue
|
|
281
|
+
|
|
282
|
+
if 'Package id 0:' in line and 'coretemp' in current_module:
|
|
283
|
+
temps["CPU"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
|
|
284
|
+
elif 'GPU:' in line and 'thinkpad' in current_module:
|
|
285
|
+
temps["GPU"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
|
|
286
|
+
elif 'Composite:' in line and 'nvme' in current_module:
|
|
287
|
+
temps["NVMe"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
|
|
288
|
+
elif 'temp1:' in line and 'acpitz' in current_module:
|
|
289
|
+
temps["Board"] = {"current": current_temp, "high": high_temp, "crit": crit_temp}
|
|
290
|
+
|
|
291
|
+
return temps
|
|
292
|
+
except (FileNotFoundError, Exception):
|
|
293
|
+
return temps
|
|
294
|
+
|
|
295
|
+
def _get_pid_to_container_map(self) -> Dict[int, str]:
|
|
296
|
+
"""
|
|
297
|
+
Builds a mapping from host PID to Docker container name.
|
|
298
|
+
Returns an empty dictionary if Docker is unavailable or fails.
|
|
299
|
+
"""
|
|
300
|
+
if docker is None:
|
|
301
|
+
return {}
|
|
302
|
+
|
|
303
|
+
pid_map = {}
|
|
304
|
+
try:
|
|
305
|
+
client = docker.APIClient(base_url='unix://var/run/docker.sock', timeout=1)
|
|
306
|
+
if not client.ping():
|
|
307
|
+
return {}
|
|
308
|
+
|
|
309
|
+
containers = client.containers()
|
|
310
|
+
for container_info in containers:
|
|
311
|
+
container_id = container_info['Id']
|
|
312
|
+
container_name = container_info['Names'][0].lstrip('/')
|
|
313
|
+
try:
|
|
314
|
+
top_data = client.top(container=container_id)
|
|
315
|
+
if not top_data or 'Processes' not in top_data:
|
|
316
|
+
continue
|
|
317
|
+
|
|
318
|
+
pids_in_container = [int(p[1]) for p in top_data['Processes']]
|
|
319
|
+
for pid in pids_in_container:
|
|
320
|
+
pid_map[pid] = container_name
|
|
321
|
+
except Exception:
|
|
322
|
+
continue
|
|
323
|
+
except (DockerException, ConnectionError, requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError):
|
|
324
|
+
return {}
|
|
325
|
+
return pid_map
|
|
326
|
+
|
|
327
|
+
def get_top_memory_processes(self) -> List[Dict]:
|
|
328
|
+
"""
|
|
329
|
+
Gets a list of the top 5 memory-consuming processes, sorted by
|
|
330
|
+
Resident Set Size (RSS). It also includes Unique Set Size (USS)
|
|
331
|
+
if it's accessible.
|
|
332
|
+
"""
|
|
333
|
+
pid_to_container = self._get_pid_to_container_map()
|
|
334
|
+
|
|
335
|
+
container_stats = {}
|
|
336
|
+
host_processes = []
|
|
337
|
+
|
|
338
|
+
for p in psutil.process_iter(['pid', 'name', 'memory_info', 'memory_full_info', 'cmdline']):
|
|
339
|
+
try:
|
|
340
|
+
# --- Get RSS (Reliable) ---
|
|
341
|
+
mem_info = p.info['memory_info']
|
|
342
|
+
if not mem_info or not mem_info.rss:
|
|
343
|
+
continue
|
|
344
|
+
|
|
345
|
+
pid = p.info['pid']
|
|
346
|
+
rss_mb = mem_info.rss / (1024**2)
|
|
347
|
+
|
|
348
|
+
# --- Get USS (May fail due to permissions) ---
|
|
349
|
+
uss_mb = None
|
|
350
|
+
try:
|
|
351
|
+
if p.info['memory_full_info'] and hasattr(p.info['memory_full_info'], 'uss'):
|
|
352
|
+
uss_mb = p.info['memory_full_info'].uss / (1024**2)
|
|
353
|
+
except (psutil.AccessDenied, AttributeError):
|
|
354
|
+
# Silently ignore if we can't get USS, uss_mb will remain None
|
|
355
|
+
pass
|
|
356
|
+
|
|
357
|
+
proc_name = ' '.join(p.info['cmdline']) if p.info['cmdline'] else p.info['name']
|
|
358
|
+
container_name = pid_to_container.get(pid)
|
|
359
|
+
|
|
360
|
+
if container_name:
|
|
361
|
+
if container_name not in container_stats:
|
|
362
|
+
container_stats[container_name] = {
|
|
363
|
+
'name': container_name,
|
|
364
|
+
'rss_mb': 0,
|
|
365
|
+
'type': 'container',
|
|
366
|
+
'processes': []
|
|
367
|
+
}
|
|
368
|
+
container_stats[container_name]['rss_mb'] += rss_mb
|
|
369
|
+
container_stats[container_name]['processes'].append({
|
|
370
|
+
'pid': pid,
|
|
371
|
+
'name': proc_name,
|
|
372
|
+
'rss_mb': rss_mb,
|
|
373
|
+
'uss_mb': uss_mb
|
|
374
|
+
})
|
|
375
|
+
else:
|
|
376
|
+
if 'perf_monitor.py' in proc_name or sys.argv[0] in proc_name:
|
|
377
|
+
continue
|
|
378
|
+
|
|
379
|
+
host_processes.append({
|
|
380
|
+
'pid': pid,
|
|
381
|
+
'full_cmd': proc_name,
|
|
382
|
+
'rss_mb': rss_mb,
|
|
383
|
+
'uss_mb': uss_mb,
|
|
384
|
+
'type': 'process'
|
|
385
|
+
})
|
|
386
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
|
387
|
+
pass
|
|
388
|
+
|
|
389
|
+
if docker:
|
|
390
|
+
try:
|
|
391
|
+
client = docker.from_env(timeout=1)
|
|
392
|
+
for name, stats in container_stats.items():
|
|
393
|
+
try:
|
|
394
|
+
container_obj = client.containers.get(name)
|
|
395
|
+
container_id = container_obj.id
|
|
396
|
+
|
|
397
|
+
base_cgroup_path = f"/sys/fs/cgroup/system.slice/docker-{container_id}.scope"
|
|
398
|
+
if not os.path.isdir(base_cgroup_path):
|
|
399
|
+
base_cgroup_path = f"/sys/fs/cgroup/memory/docker/{container_id}"
|
|
400
|
+
if not os.path.isdir(base_cgroup_path):
|
|
401
|
+
continue
|
|
402
|
+
|
|
403
|
+
# Check for cgroup v2 file first, then fall back to v1
|
|
404
|
+
mem_v2_file = os.path.join(base_cgroup_path, 'memory.current')
|
|
405
|
+
mem_v1_file = os.path.join(base_cgroup_path, 'memory.usage_in_bytes')
|
|
406
|
+
|
|
407
|
+
total_bytes = None
|
|
408
|
+
if os.path.exists(mem_v2_file):
|
|
409
|
+
with open(mem_v2_file, 'r') as f:
|
|
410
|
+
content = f.read().strip()
|
|
411
|
+
|
|
412
|
+
if content.isdigit():
|
|
413
|
+
total_bytes = int(content)
|
|
414
|
+
elif os.path.exists(mem_v1_file):
|
|
415
|
+
with open(mem_v1_file, 'r') as f:
|
|
416
|
+
total_bytes = int(f.read().strip())
|
|
417
|
+
|
|
418
|
+
if total_bytes is not None:
|
|
419
|
+
stats['cgroup_total_mb'] = total_bytes / (1024**2)
|
|
420
|
+
|
|
421
|
+
except (DockerException, FileNotFoundError, IOError):
|
|
422
|
+
continue
|
|
423
|
+
except DockerException:
|
|
424
|
+
pass
|
|
425
|
+
|
|
426
|
+
for stats in container_stats.values():
|
|
427
|
+
sorted_procs = sorted(stats['processes'], key=lambda x: x['rss_mb'], reverse=True)
|
|
428
|
+
stats['process_count'] = len(stats['processes'])
|
|
429
|
+
stats['top_processes'] = sorted_procs[:3]
|
|
430
|
+
del stats['processes']
|
|
431
|
+
|
|
432
|
+
combined_list = list(container_stats.values()) + host_processes
|
|
433
|
+
return sorted(combined_list, key=lambda x: x.get('cgroup_total_mb', x['rss_mb']), reverse=True)[:5]
|
|
434
|
+
|
|
435
|
+
def log_top_processes(logger: logging.Logger, prefix: str, processes: List[Dict]):
|
|
436
|
+
"""Helper function to log the top 5 processes with RSS and USS."""
|
|
437
|
+
if processes:
|
|
438
|
+
# Define column widths
|
|
439
|
+
rss_col_width = 24
|
|
440
|
+
uss_col_width = 12
|
|
441
|
+
separator_width = 3
|
|
442
|
+
combined_width = rss_col_width + separator_width + uss_col_width
|
|
443
|
+
|
|
444
|
+
logger.info("")
|
|
445
|
+
logger.info(f"{prefix}: Top 5 memory consumers:")
|
|
446
|
+
logger.info(f" {'PID':<8} | {'RSS (Cgroup)':<{rss_col_width}} | {'USS':>{uss_col_width}} | Command")
|
|
447
|
+
|
|
448
|
+
for i, proc in enumerate(processes):
|
|
449
|
+
if proc.get('type') == 'container':
|
|
450
|
+
pid_str = "-"
|
|
451
|
+
|
|
452
|
+
rss_part = f"{proc['rss_mb']:>7.2f} MB"
|
|
453
|
+
cgroup_total_mb = proc.get('cgroup_total_mb')
|
|
454
|
+
cgroup_part = f"{cgroup_total_mb:.2f} MB" if cgroup_total_mb is not None else "N/A"
|
|
455
|
+
rss_and_cgroup_str = f"{rss_part} ({cgroup_part})"
|
|
456
|
+
|
|
457
|
+
count = proc.get('process_count', 0)
|
|
458
|
+
cmd_str = f"Container: {proc['name']} ({count} processes)"
|
|
459
|
+
|
|
460
|
+
logger.info(f"{i+1}. {pid_str:<8} | {rss_and_cgroup_str:<{combined_width}} | {cmd_str}")
|
|
461
|
+
|
|
462
|
+
for j, sub_proc in enumerate(proc.get('top_processes', [])):
|
|
463
|
+
prefix_char = "└─" if j == len(proc['top_processes']) - 1 else "├─"
|
|
464
|
+
sub_pid_str = sub_proc['pid']
|
|
465
|
+
sub_rss_str = f"{sub_proc['rss_mb']:>7.2f} MB"
|
|
466
|
+
sub_uss_mb = sub_proc.get('uss_mb')
|
|
467
|
+
sub_uss_str = f"{sub_uss_mb:>7.2f} MB" if sub_uss_mb is not None else " "
|
|
468
|
+
|
|
469
|
+
prefixed_sub_cmd = f"{prefix_char} {sub_proc['name']}"
|
|
470
|
+
|
|
471
|
+
logger.info(f" {str(sub_pid_str):<8} | {sub_rss_str:<{rss_col_width}} | {sub_uss_str:>{uss_col_width}} | {prefixed_sub_cmd}")
|
|
472
|
+
else:
|
|
473
|
+
pid_str = proc['pid']
|
|
474
|
+
rss_str = f"{proc['rss_mb']:>7.2f} MB"
|
|
475
|
+
uss_mb = proc.get('uss_mb')
|
|
476
|
+
uss_str = f"{uss_mb:>7.2f} MB" if uss_mb is not None else " "
|
|
477
|
+
cmd_str = proc['full_cmd']
|
|
478
|
+
|
|
479
|
+
logger.info(f"{i+1}. {str(pid_str):<8} | {rss_str:<{rss_col_width}} | {uss_str:>{uss_col_width}} | {cmd_str}")
|
|
480
|
+
|
|
481
|
+
@command("perf-monitor")
|
|
482
|
+
def perf_monitor(is_command=True):
|
|
483
|
+
"""Main function to run the live performance monitor as a standalone script."""
|
|
484
|
+
parser = argparse.ArgumentParser(description="A system resource monitor.")
|
|
485
|
+
parser.add_argument(
|
|
486
|
+
"--memory",
|
|
487
|
+
default=True,
|
|
488
|
+
action="store_true",
|
|
489
|
+
help="Always display the top memory-consuming processes."
|
|
490
|
+
)
|
|
491
|
+
args = subcommand_parse_args(parser, is_command)
|
|
492
|
+
|
|
493
|
+
monitor = PerfMonitor()
|
|
494
|
+
|
|
495
|
+
def clear_screen():
|
|
496
|
+
os.system('cls' if os.name == 'nt' else 'clear')
|
|
497
|
+
|
|
498
|
+
start_time = time.monotonic()
|
|
499
|
+
|
|
500
|
+
try:
|
|
501
|
+
log_top_processes(monitor._logger, "[START]", monitor.get_top_memory_processes())
|
|
502
|
+
|
|
503
|
+
while not monitor._stop_event.is_set():
|
|
504
|
+
cpu_percent = monitor.get_cpu_usage(interval=0.1)
|
|
505
|
+
cpu_count = monitor.get_cpu_count()
|
|
506
|
+
igpu_percent = monitor.get_igpu_usage()
|
|
507
|
+
gpu_percent = monitor.get_gpu_usage()
|
|
508
|
+
mem_stats = monitor.get_memory_usage()
|
|
509
|
+
storage_stats = monitor.get_storage_usage()
|
|
510
|
+
load_avg = monitor.get_load_average()
|
|
511
|
+
temps = monitor.get_temperatures()
|
|
512
|
+
|
|
513
|
+
is_oom = mem_stats["percent_used"] > HIGH_MEMORY_THRESHOLD_PERCENT
|
|
514
|
+
|
|
515
|
+
ts = time.strftime('%Y-%m-%d %H:%M:%S')
|
|
516
|
+
log_entry = (
|
|
517
|
+
f"{ts}] CPU: {cpu_percent:.2f}% | "
|
|
518
|
+
f"Mem: {mem_stats['used_gb']:.2f}/{mem_stats['total_gb']:.2f}GB ({mem_stats['percent_used']:.1f}%)"
|
|
519
|
+
)
|
|
520
|
+
monitor._logger.info(log_entry)
|
|
521
|
+
|
|
522
|
+
if args.memory or is_oom:
|
|
523
|
+
top_memory_procs = monitor.get_top_memory_processes()
|
|
524
|
+
|
|
525
|
+
if is_oom:
|
|
526
|
+
current_consumers = [p.get('pid', p.get('name')) for p in top_memory_procs]
|
|
527
|
+
if current_consumers != monitor._previous_logged_top_pids:
|
|
528
|
+
log_top_processes(monitor._logger, f"CRITICAL MEMORY {HIGH_MEMORY_THRESHOLD_PERCENT}% USED", top_memory_procs)
|
|
529
|
+
monitor._previous_logged_top_pids = current_consumers
|
|
530
|
+
else:
|
|
531
|
+
monitor._previous_logged_top_pids = []
|
|
532
|
+
|
|
533
|
+
clear_screen()
|
|
534
|
+
|
|
535
|
+
uptime_seconds = int(time.monotonic() - start_time)
|
|
536
|
+
uptime_str = time.strftime('%H:%M:%S', time.gmtime(uptime_seconds))
|
|
537
|
+
current_time_str = time.strftime('%Y-%m-%d %H:%M:%S')
|
|
538
|
+
print(f" {current_time_str} Uptime {uptime_str}")
|
|
539
|
+
|
|
540
|
+
cpu_bar = '█' * int(40 * cpu_percent / 100) + '-' * (40 - int(40 * cpu_percent / 100))
|
|
541
|
+
print(f"CPU Usage : |{cpu_bar}| {cpu_percent:.2f}%")
|
|
542
|
+
load_str = f"{load_avg[0]:.2f}, {load_avg[1]:.2f}, {load_avg[2]:.2f} / {cpu_count} Cores" if load_avg else ""
|
|
543
|
+
print(f" Load Avg {load_str} (1, 5, 15 min)")
|
|
544
|
+
|
|
545
|
+
mem_bar = '█' * int(40 * mem_stats["percent_used"] / 100) + '-' * (40 - int(40 * mem_stats["percent_used"] / 100))
|
|
546
|
+
print(f"Mem (Used) : |{mem_bar}| {mem_stats['percent_used']:.2f}%")
|
|
547
|
+
|
|
548
|
+
# Cache/Buff: {mem_stats['cache_buffers_gb']:.2f}G | Available: {mem_stats['available_gb']:.2f}G
|
|
549
|
+
print(f" Used: {mem_stats['used_gb']:.2f}G / Total: {mem_stats['total_gb']:.2f}G")
|
|
550
|
+
|
|
551
|
+
if storage_stats:
|
|
552
|
+
storage_bar = '█' * int(40 * storage_stats['percent_used'] / 100) + '-' * (40 - int(40 * storage_stats['percent_used'] / 100))
|
|
553
|
+
print(f"Storage / : |{storage_bar}| {storage_stats['percent_used']:.2f}%")
|
|
554
|
+
print(f" Used: {storage_stats['used_gb']:.2f}G / Total: {storage_stats['total_gb']:.2f}G")
|
|
555
|
+
|
|
556
|
+
if igpu_percent is not None:
|
|
557
|
+
igpu_bar = '█' * int(40 * igpu_percent / 100) + '-' * (40 - int(40 * igpu_percent / 100))
|
|
558
|
+
print(f"iGPU Usage : |{igpu_bar}| {igpu_percent:.2f}%")
|
|
559
|
+
|
|
560
|
+
if gpu_percent is not None:
|
|
561
|
+
gpu_bar = '█' * int(40 * gpu_percent / 100) + '-' * (40 - int(40 * gpu_percent / 100))
|
|
562
|
+
print(f"GPU Usage : |{gpu_bar}| {gpu_percent:.2f}%")
|
|
563
|
+
|
|
564
|
+
print()
|
|
565
|
+
|
|
566
|
+
headers = ["CPU", "GPU", "Board (ACPI)", "NVMe"]
|
|
567
|
+
keys = ["CPU", "GPU", "Board", "NVMe"]
|
|
568
|
+
values = []
|
|
569
|
+
|
|
570
|
+
for key in keys:
|
|
571
|
+
temp_data = temps.get(key)
|
|
572
|
+
value_str = "N/A"
|
|
573
|
+
if temp_data and temp_data['current'] is not None:
|
|
574
|
+
value_str = f"{temp_data['current']:.1f}°C"
|
|
575
|
+
details = []
|
|
576
|
+
if temp_data['high'] is not None:
|
|
577
|
+
details.append(f"h={temp_data['high']:.1f}")
|
|
578
|
+
if temp_data['crit'] is not None:
|
|
579
|
+
details.append(f"c={temp_data['crit']:.1f}")
|
|
580
|
+
if details:
|
|
581
|
+
value_str += f" ({','.join(details)})"
|
|
582
|
+
values.append(value_str)
|
|
583
|
+
|
|
584
|
+
widths = [max(len(h), len(v)) for h, v in zip(headers, values)]
|
|
585
|
+
|
|
586
|
+
header_line_parts = [f"{h:<{w}}" for h, w in zip(headers, widths)]
|
|
587
|
+
value_line_parts = [f"{v:<{w}}" for v, w in zip(values, widths)]
|
|
588
|
+
|
|
589
|
+
print(" | ".join(header_line_parts))
|
|
590
|
+
print(" | ".join(value_line_parts))
|
|
591
|
+
|
|
592
|
+
process_section_header = "Top 5 Memory Consumers (Sorted by Process RSS):"
|
|
593
|
+
process_lines_to_print = []
|
|
594
|
+
|
|
595
|
+
if args.memory or is_oom:
|
|
596
|
+
# Prepend the warning banner if needed
|
|
597
|
+
if is_oom:
|
|
598
|
+
process_section_header = f"CRITICAL MEMORY {HIGH_MEMORY_THRESHOLD_PERCENT}% USED: " + process_section_header
|
|
599
|
+
|
|
600
|
+
process_lines_to_print.append(process_section_header.strip())
|
|
601
|
+
process_lines_to_print.append(f" {'PID':<8} | {'RSS (Cgroup)':<12} | {'USS':>12} | Command")
|
|
602
|
+
if top_memory_procs:
|
|
603
|
+
for i, proc in enumerate(top_memory_procs):
|
|
604
|
+
if proc.get('type') == 'container':
|
|
605
|
+
pid_str = "-"
|
|
606
|
+
uss_str = " "
|
|
607
|
+
|
|
608
|
+
rss_part = f"{proc['rss_mb']:>9.2f} MB"
|
|
609
|
+
cgroup_total_mb = proc.get('cgroup_total_mb')
|
|
610
|
+
if cgroup_total_mb:
|
|
611
|
+
cgroup_total_str = f"{cgroup_total_mb:.2f} MB"
|
|
612
|
+
else:
|
|
613
|
+
cgroup_total_str = f" MB"
|
|
614
|
+
|
|
615
|
+
rss_and_total_str = f"{rss_part} ({cgroup_total_str})"
|
|
616
|
+
|
|
617
|
+
count = proc.get('process_count', 0)
|
|
618
|
+
top_procs = proc.get('top_processes', [])
|
|
619
|
+
|
|
620
|
+
raw_name = proc['name']
|
|
621
|
+
truncated_name = (raw_name[:20] + '..') if len(raw_name) > 22 else raw_name
|
|
622
|
+
if count > len(top_procs):
|
|
623
|
+
summary_text = f"({count} processes, top {len(top_procs)} shown)"
|
|
624
|
+
else:
|
|
625
|
+
summary_text = f"({count} processes)"
|
|
626
|
+
|
|
627
|
+
cmd_str = f"docker top {truncated_name} -o pid,rss,cmd {summary_text}"
|
|
628
|
+
|
|
629
|
+
process_lines_to_print.append(f"{i+1}. {str(pid_str):<8} | {rss_and_total_str:<27} | {cmd_str}")
|
|
630
|
+
|
|
631
|
+
for j, sub_proc in enumerate(top_procs):
|
|
632
|
+
is_last = (j == len(top_procs) - 1)
|
|
633
|
+
prefix = "└─" if is_last else "├─"
|
|
634
|
+
|
|
635
|
+
sub_pid_str = sub_proc['pid']
|
|
636
|
+
sub_rss_str = f"{sub_proc['rss_mb']:>7.2f} MB"
|
|
637
|
+
sub_uss_mb = sub_proc.get('uss_mb')
|
|
638
|
+
sub_uss_str = f"{sub_uss_mb:>7.2f} MB" if sub_uss_mb is not None else " "
|
|
639
|
+
|
|
640
|
+
prefixed_sub_cmd = f"{prefix} {sub_proc['name']}"
|
|
641
|
+
sub_cmd_truncated = (prefixed_sub_cmd[:65] + '..') if len(prefixed_sub_cmd) > 67 else prefixed_sub_cmd
|
|
642
|
+
process_lines_to_print.append(f" {str(sub_pid_str):<8} | {sub_rss_str:>12} | {sub_uss_str:>12} | {sub_cmd_truncated}")
|
|
643
|
+
|
|
644
|
+
else:
|
|
645
|
+
pid_str = proc['pid']
|
|
646
|
+
rss_str = f"{proc['rss_mb']:>9.2f} MB"
|
|
647
|
+
uss_mb = proc.get('uss_mb')
|
|
648
|
+
uss_str = f"{uss_mb:>7.2f} MB" if uss_mb is not None else " "
|
|
649
|
+
cmd_str = proc['full_cmd']
|
|
650
|
+
cmd_str_truncated = (cmd_str[:70] + '..') if len(cmd_str) > 72 else cmd_str
|
|
651
|
+
process_lines_to_print.append(f"{i+1}. {str(pid_str):<8} | {rss_str:<12} | {uss_str:>12} | {cmd_str_truncated}")
|
|
652
|
+
else:
|
|
653
|
+
process_lines_to_print.append("No running processes or containers found.")
|
|
654
|
+
|
|
655
|
+
if process_lines_to_print:
|
|
656
|
+
print("\n" + "\n".join(process_lines_to_print))
|
|
657
|
+
|
|
658
|
+
print("\n sudo is required for iGPU usage access. Press 'q' to exit")
|
|
659
|
+
|
|
660
|
+
time.sleep(1)
|
|
661
|
+
|
|
662
|
+
except KeyboardInterrupt:
|
|
663
|
+
print("\nExiting monitor gracefully...")
|
|
664
|
+
finally:
|
|
665
|
+
monitor.stop()
|
|
666
|
+
log_top_processes(monitor._logger, "[STOP]", monitor.get_top_memory_processes())
|
|
667
|
+
print(f"\nLog file '{monitor.log_file_name}' has been created.")
|
|
668
|
+
|
|
669
|
+
def check_docker_connection() -> Tuple[str, Optional[str]]:
|
|
670
|
+
"""
|
|
671
|
+
Checks for Docker availability and configuration issues.
|
|
672
|
+
|
|
673
|
+
Returns a tuple of (status, error_message), where status is one of:
|
|
674
|
+
'OK', 'NOT_INSTALLED', 'PERMISSION_ERROR', 'CONNECTION_ERROR'.
|
|
675
|
+
"""
|
|
676
|
+
try:
|
|
677
|
+
import docker
|
|
678
|
+
from docker.errors import DockerException
|
|
679
|
+
except ImportError:
|
|
680
|
+
return 'NOT_INSTALLED', None
|
|
681
|
+
|
|
682
|
+
try:
|
|
683
|
+
client = docker.from_env(timeout=1)
|
|
684
|
+
client.ping()
|
|
685
|
+
return 'OK', None
|
|
686
|
+
except DockerException as e:
|
|
687
|
+
if 'Permission denied' in str(e):
|
|
688
|
+
return 'PERMISSION_ERROR', str(e)
|
|
689
|
+
else:
|
|
690
|
+
return 'CONNECTION_ERROR', str(e)
|
|
691
|
+
except Exception as e:
|
|
692
|
+
return 'CONNECTION_ERROR', str(e)
|
|
693
|
+
|
|
694
|
+
if __name__ == "__main__":
|
|
695
|
+
docker_status, error_msg = check_docker_connection()
|
|
696
|
+
|
|
697
|
+
if docker_status != 'OK':
|
|
698
|
+
print("--- Docker Integration Warning ---")
|
|
699
|
+
print("Container detection will be disabled due to a configuration issue.")
|
|
700
|
+
print("To fix this, please follow the relevant steps below:\n")
|
|
701
|
+
|
|
702
|
+
if docker_status == 'NOT_INSTALLED':
|
|
703
|
+
print("1. Install the Docker SDK for Python:")
|
|
704
|
+
print(" pip install docker")
|
|
705
|
+
|
|
706
|
+
elif docker_status == 'PERMISSION_ERROR':
|
|
707
|
+
print("1. Add your user to the 'docker' group:")
|
|
708
|
+
print(" sudo usermod -aG docker ${USER}")
|
|
709
|
+
print("\n2. IMPORTANT: You must log out and log back in for this change to take effect.")
|
|
710
|
+
|
|
711
|
+
elif docker_status == 'CONNECTION_ERROR':
|
|
712
|
+
print("1. Ensure the Docker daemon is running:")
|
|
713
|
+
print(" sudo systemctl status docker")
|
|
714
|
+
print("\n2. You may have an incompatible version of the Docker SDK. This can happen with")
|
|
715
|
+
print(" very new Docker Engine releases. Try upgrading the library:")
|
|
716
|
+
print(" pip install --upgrade docker")
|
|
717
|
+
print(f"\n (Error details: {error_msg})")
|
|
718
|
+
|
|
719
|
+
print("\nContinuing without container monitoring in 5 seconds...")
|
|
720
|
+
time.sleep(5)
|
|
721
|
+
|
|
722
|
+
try:
|
|
723
|
+
by_name["perf-monitor"](False)
|
|
724
|
+
except (NameError, KeyError):
|
|
725
|
+
perf_monitor(False)
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "brainframe-sys-tools"
|
|
3
|
-
version = "0.5.
|
|
3
|
+
version = "0.5.6"
|
|
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 = [
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
brainframe_sys_tools-0.5.4/brainframe_sys_tools/brainframe_monitor/__pycache__/report.cpython-38.pyc
DELETED
|
Binary file
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/check_memory.py
RENAMED
|
File without changes
|
{brainframe_sys_tools-0.5.4 → brainframe_sys_tools-0.5.6}/brainframe_sys_tools/print_utils.py
RENAMED
|
File without changes
|