brainframe-sys-tools 0.3.19__tar.gz → 0.4__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 (22) hide show
  1. brainframe_sys_tools-0.4/COPYING +26 -0
  2. brainframe_sys_tools-0.4/PKG-INFO +24 -0
  3. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/__init__.py +1 -0
  4. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/bf_service_monitor.py +120 -8
  5. brainframe_sys_tools-0.4/brainframe_sys_tools/bf_ssh_tunnel.py +104 -0
  6. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/brainframe_monitor/benchmarker.py +9 -3
  7. brainframe_sys_tools-0.4/brainframe_sys_tools/check_memory.py +213 -0
  8. brainframe_sys_tools-0.4/brainframe_sys_tools/cli.py +59 -0
  9. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/print_utils.py +0 -1
  10. brainframe_sys_tools-0.4/brainframe_sys_tools/translations/portal.en.yml +20 -0
  11. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/pyproject.toml +18 -2
  12. brainframe_sys_tools-0.3.19/PKG-INFO +0 -19
  13. brainframe_sys_tools-0.3.19/brainframe_sys_tools/cli.py +0 -43
  14. brainframe_sys_tools-0.3.19/brainframe_sys_tools/translations/portal.en.yml +0 -18
  15. brainframe_sys_tools-0.3.19/setup.py +0 -35
  16. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/bf_info.py +0 -0
  17. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/brainframe_monitor/brainframe_monitor.py +0 -0
  18. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/brainframe_monitor/curses_utils.py +0 -0
  19. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/brainframe_monitor/fake_screen.py +0 -0
  20. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/brainframe_monitor/report.py +0 -0
  21. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/brainframe_monitor/requirements.txt +0 -0
  22. {brainframe_sys_tools-0.3.19 → brainframe_sys_tools-0.4}/brainframe_sys_tools/command_utils.py +0 -0
@@ -0,0 +1,26 @@
1
+ Copyright (C) 2020, Dilili Labs INC, all rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this
7
+ list of conditions and the following disclaimer.
8
+
9
+ 2. Redistributions in binary form must reproduce the above copyright notice,
10
+ this list of conditions and the following disclaimer in the documentation
11
+ and/or other materials provided with the distribution.
12
+
13
+ 3. Neither the name of the copyright holder nor the names of its contributors
14
+ may be used to endorse or promote products derived from this software without
15
+ specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.1
2
+ Name: brainframe-sys-tools
3
+ Version: 0.4
4
+ Summary: This is the package including tools for BrainFrame developers to monitor and debug the system.
5
+ License: BSD License
6
+ Author: Stephen Li
7
+ Author-email: stephen@aotu.ai
8
+ Requires-Python: >=3.9,<4.0
9
+ Classifier: License :: OSI Approved :: BSD License
10
+ Classifier: License :: Other/Proprietary License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Dist: PyYAML (>=6.0.2,<7.0.0)
18
+ Requires-Dist: apscheduler (>=3.10.4,<4.0.0)
19
+ Requires-Dist: brainframe-api (>=0.29.1,<0.30.0)
20
+ Requires-Dist: brainframe_apps (>=0.4.3.5,<0.5.0.0)
21
+ Requires-Dist: psutil (>=5.8.0,<6.0.0)
22
+ Requires-Dist: python_i18n (>=0.3.9,<0.4.0)
23
+ Requires-Dist: requests (>=2.32.3,<3.0.0)
24
+ Requires-Dist: tabulate (>=0.8.9,<0.9.0)
@@ -2,3 +2,4 @@ from .cli import cli_main
2
2
  from .brainframe_monitor.brainframe_monitor import fps_monitor
3
3
  from .bf_info import sys_info
4
4
  from .bf_service_monitor import service_monitor
5
+ from .bf_ssh_tunnel import ssh_tunnel
@@ -15,16 +15,22 @@ from brainframe.api import BrainFrameAPI
15
15
  from brainframe_sys_tools.bf_info import save_sys_info
16
16
  from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
17
17
 
18
+ from apscheduler.schedulers.background import BackgroundScheduler
19
+ from apscheduler.triggers.cron import CronTrigger
20
+
18
21
 
19
22
  class HeartBeat:
20
- def __init__(self, log_path, interval, threshold):
23
+ def __init__(
24
+ self, log_path, interval, threshold, log_save=False, restart_cron=None
25
+ ):
21
26
 
22
27
  self.interval = int(interval)
23
28
  self.threshold = int(threshold)
29
+ self.log_save = log_save
24
30
 
25
31
  if os.path.isdir(log_path) is not True:
26
32
  print(f"{log_path} is invalid!")
27
- return
33
+ exit(1)
28
34
  self.log_path = log_path
29
35
 
30
36
  self.time_0 = datetime.now()
@@ -33,6 +39,18 @@ class HeartBeat:
33
39
  self.brainframe_log_filename = None
34
40
  self.heartbeat_log_open(interval, threshold)
35
41
 
42
+ self.d_status = {}
43
+ # add BackgroundScheduler
44
+ self.bgscheduler = None
45
+ self.restart_timeout = None
46
+ # Schedule the job to run daily/weekly/month at midnight (00:00)
47
+ if restart_cron is not None:
48
+ # add BackgroundScheduler for timed task
49
+ self.bgscheduler = BackgroundScheduler()
50
+ # use CronTrigger parse Cron style string
51
+ self.cron_trigger = CronTrigger.from_crontab(restart_cron)
52
+ self.bgscheduler.add_job(self._cron_job, self.cron_trigger)
53
+
36
54
  def heartbeat_log_open(self, interval, threshold):
37
55
  self.time_0 = datetime.now()
38
56
  self.log_path_prefix = str(self.log_path) + f"/{self.time_0.isoformat()}_"
@@ -59,9 +77,12 @@ class HeartBeat:
59
77
 
60
78
  def restart_brainframe(self):
61
79
  self.heartbeat_log(f"Stop brainframe")
62
- self.save_brainframe_logs()
63
- brainframe_sys_info_filename = self.log_path_prefix + "sys.info"
64
- save_sys_info(brainframe_sys_info_filename)
80
+
81
+ if self.log_save:
82
+ self.save_brainframe_logs()
83
+ brainframe_sys_info_filename = self.log_path_prefix + "sys.info"
84
+ save_sys_info(brainframe_sys_info_filename)
85
+
65
86
  self.stop_brainframe()
66
87
  self.heartbeat_log(f"Save brainframe logs at {self.brainframe_log_filename}")
67
88
  self.heartbeat_log_close()
@@ -132,24 +153,79 @@ class HeartBeat:
132
153
  return heartbeat_val, heartbeat_response
133
154
 
134
155
  def heartbeat_monitor(self, api):
156
+ # start cron scheduler
157
+ self.start_cron_scheduler()
135
158
  has_restarted = False
136
159
  while True:
137
160
  heartbeat_val, heartbeat_response = self.wait_for_heartbeat(
138
161
  lambda: api.version(self.threshold), self.threshold
139
162
  )
163
+
140
164
  if heartbeat_response:
141
165
  has_restarted = False
142
166
  self.heartbeat_log(
143
167
  f"version {heartbeat_response} heartbeat OK: response time - {heartbeat_val}"
144
168
  )
169
+
170
+ # zonestatus monitor.
171
+ self.zone_status_monitor(api)
172
+ # check if restart-cron task is timeout, need to deal.
173
+ if self.restart_timeout:
174
+ self.heartbeat_log(f"cron task timeout, to restart service")
175
+ self.restart_brainframe()
176
+ has_restarted = True
177
+ self.restart_timeout = None
145
178
  else:
146
179
  self.heartbeat_log(f"heartbeat failed: timeout - {heartbeat_val}")
147
180
  if not has_restarted:
148
181
  self.restart_brainframe()
149
182
  has_restarted = True
150
183
 
184
+ if self.restart_timeout:
185
+ self.restart_timeout = None
186
+
151
187
  sleep(self.interval)
152
188
 
189
+ def zone_status_monitor(self, api):
190
+ # check api/streams/status, analyze result is normal or not
191
+ status_val, status_response = self.wait_for_heartbeat(
192
+ lambda: api.get_latest_zone_statuses(self.threshold), self.threshold
193
+ )
194
+
195
+ if status_response:
196
+ # streamid,zonestatus = next(iter(status_response.items()))
197
+ # tstamp = zonestatus["Screen"].tstamp
198
+ has_changed = []
199
+ no_change = []
200
+ for streamid, zonestatus in status_response.items():
201
+ last_tstamp = self.d_status.get(streamid, 0.0)
202
+ tstamp = zonestatus["Screen"].tstamp
203
+
204
+ if last_tstamp != tstamp:
205
+ has_changed.append(streamid)
206
+ self.d_status[streamid] = tstamp
207
+ else:
208
+ no_change.append((streamid, tstamp))
209
+
210
+ self.heartbeat_log(
211
+ f"latest_zone_status OK: changed:{has_changed}, no change:{no_change}, response time - {status_val}"
212
+ )
213
+ else:
214
+ self.heartbeat_log(
215
+ f"latest_zone_status failed: timeout or no zonestatus - {status_val}"
216
+ )
217
+
218
+ def _cron_job(self):
219
+ # cron job for restart.
220
+ print(f"_cron_job: {self.cron_trigger}")
221
+ self.restart_timeout = True
222
+
223
+ def start_cron_scheduler(self):
224
+ # if set bgscheduler, start scheduler
225
+ if self.bgscheduler is not None:
226
+ self.heartbeat_log(f"start cron scheduler, {self.cron_trigger}")
227
+ self.bgscheduler.start()
228
+
153
229
 
154
230
  def _parse_args():
155
231
  parser = ArgumentParser(
@@ -193,10 +269,30 @@ def _parse_args():
193
269
  )
194
270
  parser.add_argument(
195
271
  "--start-now",
196
- default=True,
272
+ action="store_true",
197
273
  help="Start the brainframe service. Default: %(default)s",
198
274
  )
199
275
 
276
+ parser.add_argument(
277
+ "--log-save",
278
+ action="store_true",
279
+ help="Brainframe log and sys.info will be saved when the service is unavailable. Default: %(default)s",
280
+ )
281
+
282
+ parser.add_argument(
283
+ "--restart-cron",
284
+ default=None,
285
+ type=str,
286
+ help="""Brainframe service will restart on midnight, using Cron-style schedule string (e.g., '* * * * *'), Default: %(default)s.
287
+ For example, '0 0 * * 3' is on midnight every Thursday,
288
+ The first 0: Minute (0 - 59)
289
+ The second 0: Hour (0 - 23)
290
+ The third *: Day of the month (1 - 31)
291
+ The fourth *: Month (1 - 12)
292
+ The fifth 3: Day of the week (0 - 6 for Monday to Sunday, accroding to apscheduler)
293
+ When you use an asterisk (*) in any of these fields, it represents 'every'.""",
294
+ )
295
+
200
296
  args = subcommand_parse_args(parser)
201
297
  return args
202
298
 
@@ -205,10 +301,27 @@ def _parse_args():
205
301
  def service_monitor():
206
302
  args = _parse_args()
207
303
 
304
+ # if restart_cron is set, check if cron string is fine.
305
+ if args.restart_cron:
306
+ try:
307
+ # use from_crontab() create CronTrigger instance
308
+ trigger = CronTrigger.from_crontab(args.restart_cron)
309
+ print(f"restart-cron: {trigger}")
310
+ except (ValueError, KeyError) as e:
311
+ # cron string invalid
312
+ print(f"Invalid argument restart-cron format: {e}")
313
+ exit(1)
314
+
208
315
  # Connect to the BrainFrame Server
209
316
  server_url = args.server_url
210
317
 
211
- hb = HeartBeat(args.log_path, args.interval, args.threshold)
318
+ hb = HeartBeat(
319
+ args.log_path,
320
+ args.interval,
321
+ args.threshold,
322
+ log_save=args.log_save,
323
+ restart_cron=args.restart_cron,
324
+ )
212
325
 
213
326
  if args.start_now:
214
327
  hb.start_brainframe()
@@ -228,4 +341,3 @@ def service_monitor():
228
341
 
229
342
  if __name__ == "__main__":
230
343
  by_name["service_monitor"]()
231
-
@@ -0,0 +1,104 @@
1
+ #
2
+ # Copyright (c) 2021 Dilili Labs, Inc. All rights reserved. Contains Dilili Labs Proprietary Information. RESTRICTED COMPUTER SOFTWARE. LIMITED RIGHTS DATA.
3
+ #
4
+
5
+ import subprocess
6
+ from argparse import ArgumentParser
7
+
8
+ from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
9
+
10
+
11
+ def _parse_args():
12
+ parser = ArgumentParser("brainframe-sys-tools ssh_tunnel")
13
+ parser.add_argument(
14
+ "-s",
15
+ "--server-url",
16
+ default="dililitechnology.com",
17
+ help="The SSH server url or ip, Default is %(default)s.",
18
+ )
19
+ parser.add_argument(
20
+ "-u",
21
+ "--user",
22
+ default="ubuntu",
23
+ help="Username to access the SSH server, Default is %(default)s.",
24
+ )
25
+ parser.add_argument(
26
+ "-p",
27
+ "--port",
28
+ default="22",
29
+ help="The SSH server port, Default is %(default)s.",
30
+ )
31
+ parser.add_argument(
32
+ "-r",
33
+ "--remoteforward",
34
+ action="append",
35
+ required=True,
36
+ help="The SSH remote forward port(s) and local port(s), \
37
+ format is 'remoteport:localhost:localport'. Use multiple -r to specify additional rules. \
38
+ For example '-r 8088:localhost:80', on remote ssh server, you can use 'localhost:8088' to access local port 80",
39
+ )
40
+ parser.add_argument(
41
+ "-i",
42
+ "--identity_file",
43
+ default=None,
44
+ help="The SSH identity file, Default is %(default)s.",
45
+ )
46
+ parser.add_argument(
47
+ "-o",
48
+ "--option",
49
+ default=["ExitOnForwardFailure=yes"],
50
+ action="append",
51
+ help="SSH client options, Default is %(default)s. \
52
+ Use muliple -o to specify more options, for example '-o ServerAliveInterval=120 -o ServerAliveCountMax=3'.",
53
+ )
54
+
55
+ args = subcommand_parse_args(parser)
56
+
57
+ return args
58
+
59
+
60
+ def run_command_list(commandlst):
61
+ print(" ".join(commandlst))
62
+ print("Press Ctrl-C, to quit")
63
+
64
+ try:
65
+ result = subprocess.run(
66
+ commandlst, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
67
+ )
68
+
69
+ if result.stdout:
70
+ print(result.stdout)
71
+ if result.stderr:
72
+ print(f"Error: {result.stderr}")
73
+ except KeyboardInterrupt:
74
+ print(" Process was interrupted by user")
75
+
76
+
77
+ @command("ssh_tunnel")
78
+ def ssh_tunnel():
79
+ args = _parse_args()
80
+
81
+ # Build the SSH command
82
+ ssh_command = ["ssh", "-N", "-p", args.port]
83
+ if args.identity_file:
84
+ ssh_command.extend(["-i", args.identity_file])
85
+
86
+ # Add each remote forward rule to the SSH command
87
+ for rf in args.remoteforward:
88
+ ssh_command.extend(["-R", rf])
89
+
90
+ # Add each option to command list
91
+ for option in args.option:
92
+ ssh_command.extend(["-o", option])
93
+
94
+ ssh_command.append(f"{args.user}@{args.server_url}")
95
+ # start ssh tunnel
96
+ print(
97
+ "Note: After establishing an SSH reverse tunnel, the remote host can access the locally mapped ports and services.\n"
98
+ " Please ensure the privacy and security of the local host."
99
+ )
100
+ run_command_list(ssh_command)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ by_name["ssh_tunnel"]()
@@ -251,7 +251,7 @@ class Benchmarker:
251
251
  throughput_fps,
252
252
  self.fps_lock_range,
253
253
  self.fps_min,
254
- self.fps_max
254
+ self.fps_max,
255
255
  )
256
256
 
257
257
  row += 1
@@ -288,7 +288,11 @@ class Benchmarker:
288
288
  row += 2
289
289
 
290
290
  # Output press key prompt and debug information
291
- screen.addstr(row, 5, f"Total {self.total_streams} streams measured. Press q to quit {debug_print}")
291
+ screen.addstr(
292
+ row,
293
+ 5,
294
+ f"Total {self.total_streams} streams measured. Press q to quit {debug_print}",
295
+ )
292
296
 
293
297
  screen.refresh()
294
298
 
@@ -520,7 +524,9 @@ def test_plot():
520
524
  curr_fps_min, curr_fps_max, cfg = benchmarker.save_fps_throughput(
521
525
  fps_hist_buf_len, plt_height_limit, plt_width, fps_hist, throughput, False
522
526
  )
523
- plot_txt, plot_n_rows, debug_print = plot(fps_hist, curr_fps_min, curr_fps_max, cfg)
527
+ plot_txt, plot_n_rows, debug_print = plot(
528
+ fps_hist, curr_fps_min, curr_fps_max, cfg
529
+ )
524
530
  print(f"{plot_txt}\nIndex: {i}, fps: {value}\n{debug_print}")
525
531
 
526
532
 
@@ -0,0 +1,213 @@
1
+ import os
2
+ import resource
3
+ import random
4
+ import psutil
5
+ import argparse
6
+ from datetime import datetime
7
+ import time
8
+
9
+
10
+ def read_file(file_path):
11
+ with open(file_path, "r") as f:
12
+ return f.read().strip()
13
+
14
+
15
+ def bytes_to_mib(bytes):
16
+ return int(bytes) / 1024 / 1024
17
+
18
+
19
+ def cgroup_usage(uid):
20
+ limit_in_bytes = read_file(
21
+ f"/sys/fs/cgroup/memory/user.slice/user-{uid}.slice/memory.limit_in_bytes"
22
+ )
23
+ max_usage_in_bytes = read_file(
24
+ f"/sys/fs/cgroup/memory/user.slice/user-{uid}.slice/memory.max_usage_in_bytes"
25
+ )
26
+ usage_in_bytes = read_file(
27
+ f"/sys/fs/cgroup/memory/user.slice/user-{uid}.slice/memory.usage_in_bytes"
28
+ )
29
+ return limit_in_bytes, max_usage_in_bytes, usage_in_bytes
30
+
31
+
32
+ def print_cgroup_usage(uid):
33
+ limit_in_bytes, max_usage_in_bytes, usage_in_bytes = cgroup_usage(uid)
34
+ print(f"/sys/fs/cgroup/memory/user.slice/user-{uid}.slice/")
35
+ print(f" Limit in bytes: {bytes_to_mib(limit_in_bytes)} MiB")
36
+ print(f" Max usage in bytes: {bytes_to_mib(max_usage_in_bytes)} MiB")
37
+ print(f" Usage in bytes: {bytes_to_mib(usage_in_bytes)} MiB")
38
+
39
+
40
+ def print_resource_usage():
41
+ # Print memory usage
42
+ usage = resource.getrusage(resource.RUSAGE_SELF)
43
+ print(f"resource.getrusage()")
44
+ print(f" Memory Usage: {usage.ru_maxrss / 1024} MiB bytes")
45
+
46
+
47
+ def process_memory_info(pid):
48
+ try:
49
+ process = psutil.Process(pid)
50
+ process_mem_info = process.memory_info()
51
+ rss_in_bytes = process_mem_info.rss # in bytes
52
+ return rss_in_bytes
53
+ except psutil.NoSuchProcess:
54
+ return 0
55
+
56
+
57
+ def print_process_memory_info(pid):
58
+ rss_in_bytes = process_memory_info(pid)
59
+ print(f"psutil.Process({pid}).memory_info()")
60
+ if rss_in_bytes is not None:
61
+ print(f" RSS: {bytes_to_mib(rss_in_bytes)} MiB") # convert bytes to MiB
62
+ else:
63
+ print(f" No such process")
64
+
65
+
66
+ def system_memory_usage():
67
+ # Get the system memory usage
68
+ mem_info = psutil.virtual_memory()
69
+
70
+ # Total physical memory
71
+ total = mem_info.total # in bytes
72
+
73
+ # Available physical memory
74
+ available = mem_info.available # in bytes
75
+
76
+ # Used physical memory
77
+ used = mem_info.used # in bytes
78
+
79
+ # Memory used for buffering
80
+ buffers = mem_info.buffers if hasattr(mem_info, "buffers") else 0 # in bytes
81
+
82
+ # Memory used for caching
83
+ cached = mem_info.cached if hasattr(mem_info, "cached") else 0 # in bytes
84
+ return total, available, used, buffers, cached
85
+
86
+
87
+ def print_system_memory_usage():
88
+ total, available, used, buffers, cached = system_memory_usage()
89
+ print(f"psutil.virtual_memory()")
90
+ print(f" Total physical memory: {bytes_to_mib(total)} MiB")
91
+ print(f" Available physical memory: {bytes_to_mib(available)} MiB")
92
+ print(f" Used physical memory: {bytes_to_mib(used)} MiB")
93
+ print(f" Buffered memory: {bytes_to_mib(buffers)} MiB")
94
+ print(f" Cached memory: {bytes_to_mib(cached)} MiB")
95
+
96
+
97
+ def draw_bar_chart(data, graph_max):
98
+ colors = ["\033[91m", "\033[92m", "\033[93m", "\033[94m", "\033[95m", "\033[0m"]
99
+ for i in range(len(data)):
100
+ label, min_val, value, max_val = data[i]
101
+ value = max(min_val, min(value, max_val))
102
+
103
+ # Normalize the value to the range of the graph
104
+ normalized_value = (
105
+ int((value - min_val) / (max_val - min_val) * graph_max)
106
+ if max_val != min_val
107
+ else 0
108
+ )
109
+
110
+ # Draw the label, min, max, and value with color
111
+ color = colors[i % len(colors)]
112
+ pct = value * 100 / max_val
113
+ print(
114
+ f"{label:<10} {min_val:<2}[{color}{'|' * normalized_value}\033[0m {value:<5} {' ' * (graph_max - normalized_value)}{pct:.2f}%] {max_val:<5}"
115
+ )
116
+
117
+
118
+ def monitor_memory(uid, pid):
119
+ total, available, used, buffers, cached = system_memory_usage()
120
+ limit_in_bytes, max_usage_in_bytes, usage_in_bytes = cgroup_usage(uid)
121
+ rss_in_bytes = process_memory_info(pid)
122
+ data = [
123
+ (
124
+ " system used / system total",
125
+ 0,
126
+ int(bytes_to_mib(used)),
127
+ int(bytes_to_mib(total)),
128
+ ),
129
+ (
130
+ "cgroup usage / system used",
131
+ 0,
132
+ int(bytes_to_mib(usage_in_bytes)),
133
+ int(bytes_to_mib(used)),
134
+ ),
135
+ (
136
+ " process rss / cgroup usage",
137
+ 0,
138
+ int(bytes_to_mib(rss_in_bytes)),
139
+ int(bytes_to_mib(usage_in_bytes)),
140
+ ),
141
+ ]
142
+ draw_bar_chart(data, 50)
143
+
144
+
145
+ def main():
146
+ parser = argparse.ArgumentParser(description="Get memory usage for a process.")
147
+ parser.add_argument(
148
+ "-u",
149
+ "--uid",
150
+ type=int,
151
+ default=os.getuid(),
152
+ help="The process ID to get memory usage for.",
153
+ )
154
+
155
+ parser.add_argument(
156
+ "-p",
157
+ "--pid",
158
+ type=int,
159
+ default=os.getpid(),
160
+ help="The process ID to get memory usage for.",
161
+ )
162
+
163
+ parser.add_argument(
164
+ "-i",
165
+ "--interval",
166
+ type=int,
167
+ default=60,
168
+ help="Interval for the memory usage monitor.",
169
+ )
170
+
171
+ parser.add_argument(
172
+ "-k",
173
+ "--key",
174
+ action="store_true",
175
+ help="Wait for a key to monitor the memory usage.",
176
+ )
177
+
178
+ args = parser.parse_args()
179
+
180
+ print(f"User ID: {args.uid}")
181
+ print(f"Process ID: {args.pid}")
182
+
183
+ print_system_memory_usage()
184
+ # No way to specify pid
185
+ # print_resource_usage()
186
+ print_cgroup_usage(args.uid)
187
+ print_process_memory_info(args.pid)
188
+
189
+ if args.key:
190
+ print("Enter to continue, Q to quit: ")
191
+
192
+ while True:
193
+ # Current date and time
194
+ now = datetime.now()
195
+
196
+ # Format timestamp
197
+ timestamp = now.strftime("%d-%m-%Y %H:%M:%S")
198
+
199
+ print(timestamp)
200
+
201
+ monitor_memory(args.uid, args.pid)
202
+
203
+ if args.key:
204
+ # wait for a key press
205
+ key = input()
206
+ if key == "q" or key == "Q":
207
+ break
208
+ else:
209
+ time.sleep(args.interval)
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()
@@ -0,0 +1,59 @@
1
+ import os
2
+
3
+ os.environ["BF_LOG_PRINT"] = "TRUE"
4
+
5
+ import signal
6
+ import sys
7
+ from argparse import ArgumentParser
8
+
9
+ import i18n
10
+ import yaml
11
+ from brainframe_sys_tools import command_utils, print_utils
12
+
13
+
14
+ def add_translations(translations, prefix=""):
15
+ for key, value in translations.items():
16
+ full_key = f"{prefix}.{key}" if prefix else key
17
+ if isinstance(value, dict):
18
+ add_translations(value, full_key)
19
+ else:
20
+ i18n.add_translation(full_key, value)
21
+
22
+
23
+ def cli_main():
24
+ i18n.load_path.append(_TRANSLATIONS_PATH)
25
+
26
+ # Load translations manually
27
+ translation_file = os.path.join(_TRANSLATIONS_PATH, "portal.en.yml")
28
+ if os.path.exists(translation_file):
29
+ with open(translation_file, "r") as file:
30
+ translations = yaml.safe_load(file)
31
+ add_translations(translations)
32
+
33
+ parser = ArgumentParser(
34
+ description=i18n.t("en.portal.description"), usage=i18n.t("en.portal.usage")
35
+ )
36
+
37
+ parser.add_argument(
38
+ "command", default=None, nargs="?", help=i18n.t("en.portal.command-help")
39
+ )
40
+
41
+ args = parser.parse_args(sys.argv[1:2])
42
+
43
+ if args.command is None:
44
+ parser.print_help()
45
+ elif args.command in command_utils.by_name:
46
+ command = command_utils.by_name[args.command]
47
+ command()
48
+ else:
49
+ error_message = i18n.t("portal.unknown-command")
50
+ error_message = error_message.format(command=args.command)
51
+ print_utils.print_color(
52
+ error_message, color=print_utils.Color.RED, file=sys.stderr
53
+ )
54
+ parser.print_help()
55
+
56
+
57
+ _TRANSLATIONS_PATH = os.path.join(os.path.dirname(__file__), "translations")
58
+ if __name__ == "__main__":
59
+ cli_main()
@@ -32,4 +32,3 @@ def _check_no_color(color: Color) -> Color:
32
32
  if "NO_COLOR" in os.environ:
33
33
  return Color.END
34
34
  return color
35
-
@@ -0,0 +1,20 @@
1
+ en:
2
+ portal:
3
+ description: "brainframe-sys-tools is a group of commands written in Python. They
4
+ help to monitor brainframe system and debug the system deployment related issues.
5
+ To see options of each command, run \"brainframe-sys-tools {command} --help\"."
6
+ usage: >-
7
+ brainframe-sys-tools <command> [<args>]
8
+
9
+ commands:
10
+ fps_monitor
11
+ service_monitor
12
+ sys_info
13
+ ssh_tunnel
14
+
15
+ Examples:
16
+ brainframe-sys-tools fps_monitor
17
+
18
+ command-help: "The brainframe-sys-tools command to run"
19
+ unknown-command: "Unknown command: {command}"
20
+ interrupted: "The operation was interrupted"
@@ -1,14 +1,30 @@
1
1
  [tool.poetry]
2
2
  name = "brainframe-sys-tools"
3
- version = "0.3.19"
3
+ version = "0.4"
4
4
  description = "This is the package including tools for BrainFrame developers to monitor and debug the system."
5
5
  authors = ["Stephen Li <stephen@aotu.ai>"]
6
+ license = "BSD License"
7
+ classifiers = [
8
+ "License :: OSI Approved :: BSD License",
9
+ "Programming Language :: Python :: 3.10",
10
+ "Programming Language :: Python :: 3.12",
11
+ ]
6
12
 
7
13
  [tool.poetry.dependencies]
8
- python = "^2.7 || ^3.0"
14
+ python = "^3.9,<4.0"
15
+ python_i18n = "^0.3.9"
16
+ PyYAML = "^6.0.2"
17
+ requests = "^2.32.3"
18
+ brainframe_apps = "^0.4.3.5"
9
19
  brainframe-api = "^0.29.1"
20
+ apscheduler = "^3.10.4"
21
+ psutil = "^5.8.0"
22
+ tabulate = "^0.8.9"
10
23
 
11
24
  [tool.poetry.dev-dependencies]
25
+ black = "^22.10.0"
26
+ isort = "^5.7.0,<5.8.0"
27
+ typing-extensions = "^4.10.0"
12
28
 
13
29
  [tool.poetry.scripts]
14
30
  brainframe-sys-tools = 'brainframe_sys_tools.cli:cli_main'
@@ -1,19 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: brainframe-sys-tools
3
- Version: 0.3.19
4
- Summary: This is the package including tools for BrainFrame developers to monitor and debug the system.
5
- Author: Stephen Li
6
- Author-email: stephen@aotu.ai
7
- Requires-Python: >=2.7,<4.0
8
- Classifier: Programming Language :: Python :: 2
9
- Classifier: Programming Language :: Python :: 2.7
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.4
12
- Classifier: Programming Language :: Python :: 3.5
13
- Classifier: Programming Language :: Python :: 3.6
14
- Classifier: Programming Language :: Python :: 3.7
15
- Classifier: Programming Language :: Python :: 3.8
16
- Classifier: Programming Language :: Python :: 3.9
17
- Classifier: Programming Language :: Python :: 3.10
18
- Classifier: Programming Language :: Python :: 3.11
19
- Requires-Dist: brainframe-api (>=0.29.1,<0.30.0)
@@ -1,43 +0,0 @@
1
- import os
2
- os.environ['BF_LOG_PRINT'] = 'TRUE'
3
-
4
- import signal
5
- import sys
6
- from argparse import ArgumentParser
7
-
8
- import i18n
9
- from brainframe_sys_tools import print_utils
10
- from brainframe_sys_tools import command_utils
11
-
12
-
13
- def cli_main():
14
- i18n.load_path.append(_TRANSLATIONS_PATH)
15
-
16
- parser = ArgumentParser(
17
- description=i18n.t("portal.description"), usage=i18n.t("portal.usage")
18
- )
19
-
20
- parser.add_argument(
21
- "command", default=None, nargs="?", help=i18n.t("portal.command-help")
22
- )
23
-
24
- args = parser.parse_args(sys.argv[1:2])
25
-
26
- if args.command is None:
27
- parser.print_help()
28
- elif args.command in command_utils.by_name:
29
- command = command_utils.by_name[args.command]
30
- command()
31
- else:
32
- error_message = i18n.t("portal.unknown-command")
33
- error_message = error_message.format(command=args.command)
34
- print_utils.print_color(
35
- error_message, color=print_utils.Color.RED, file=sys.stderr
36
- )
37
- parser.print_help()
38
-
39
-
40
- _TRANSLATIONS_PATH = os.path.join(os.path.dirname(__file__), "translations")
41
-
42
- if __name__ == "__main__":
43
- cli_main()
@@ -1,18 +0,0 @@
1
- en:
2
- description: "brainframe-sys-tools is a group of commands written in Python. They
3
- help to monitor brainframe system and debug the system deployment related issues.
4
- To see options of each command, run \"brainframe-sys-tools {command} --help\"."
5
- usage: >-
6
- brainframe-sys-tools <command> [<args>]
7
-
8
- commands:
9
- fps_monitor
10
- service_monitor
11
- sys_info
12
-
13
- Examples:
14
- brainframe-sys-tools fps_monitor
15
-
16
- command-help: "The brainframe-sys-tools command to run"
17
- unknown-command: "Unknown command: {command}"
18
- interrupted: "The operation was interrupted"
@@ -1,35 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- from setuptools import setup
3
-
4
- packages = \
5
- ['brainframe_sys_tools', 'brainframe_sys_tools.brainframe_monitor']
6
-
7
- package_data = \
8
- {'': ['*'], 'brainframe_sys_tools': ['translations/*']}
9
-
10
- install_requires = \
11
- ['brainframe-api>=0.29.1,<0.30.0']
12
-
13
- entry_points = \
14
- {'console_scripts': ['brainframe-sys-tools = '
15
- 'brainframe_sys_tools.cli:cli_main']}
16
-
17
- setup_kwargs = {
18
- 'name': 'brainframe-sys-tools',
19
- 'version': '0.3.19',
20
- 'description': 'This is the package including tools for BrainFrame developers to monitor and debug the system.',
21
- 'long_description': 'None',
22
- 'author': 'Stephen Li',
23
- 'author_email': 'stephen@aotu.ai',
24
- 'maintainer': 'None',
25
- 'maintainer_email': 'None',
26
- 'url': 'None',
27
- 'packages': packages,
28
- 'package_data': package_data,
29
- 'install_requires': install_requires,
30
- 'entry_points': entry_points,
31
- 'python_requires': '>=2.7,<4.0',
32
- }
33
-
34
-
35
- setup(**setup_kwargs)