brainframe-sys-tools 0.3.19__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.
@@ -0,0 +1,19 @@
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)
@@ -0,0 +1,4 @@
1
+ from .cli import cli_main
2
+ from .brainframe_monitor.brainframe_monitor import fps_monitor
3
+ from .bf_info import sys_info
4
+ from .bf_service_monitor import service_monitor
@@ -0,0 +1,155 @@
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 json
6
+ import subprocess
7
+ from argparse import ArgumentParser
8
+
9
+ import requests
10
+
11
+ from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
12
+
13
+
14
+ header = [
15
+ "Copyright (c) 2021 Dilili Labs, Inc. All rights reserved.\n\n"
16
+ "bf_info utility checks BrainFrame system information and all inference computing dependencies.\n"
17
+ "=======\n"
18
+ ]
19
+
20
+ footer = ["\n\n"]
21
+
22
+ #
23
+ # Check if BrainFrame is still alive?
24
+ #
25
+ # curl http://localhost/api/version
26
+ #
27
+ # Check if BrainFrame has proper license installed?
28
+ #
29
+ # curl http://localhost/api/license
30
+ #
31
+ # Check all VisionCapsules configurations
32
+ #
33
+ # curl http://localhost/api/plugins
34
+ #
35
+ # Check all BrainFrame stream configurations
36
+ #
37
+ # curl http://localhost/api/streams
38
+ #
39
+ # Check if BrainFrame has connected to a stream at some point
40
+ #
41
+ # curl http://localhost/api/streams/status
42
+ #
43
+ # This will continuously pull uoutput from BrainFrame for all streams, including
44
+ # the zone status, timestamp. Let's don't do this in this tool
45
+ #
46
+ # curl http://localhost/api/streams/statuses
47
+ #
48
+
49
+ cmdlines = [
50
+ "date",
51
+ "date -u",
52
+ "uptime",
53
+ "uptime -s",
54
+ "cat /etc/os-release",
55
+ "uname -a",
56
+ "ldd --version",
57
+ "cat /proc/cpuinfo",
58
+ "cat /etc/docker/daemon.json",
59
+ "nvidia-smi",
60
+ "whereis nvidia",
61
+ "modinfo nvidia",
62
+ "dpkg -l | grep nvidia",
63
+ "apt list --upgradable",
64
+ "ls /dev/dri -l",
65
+ "df -h",
66
+ "which brainframe",
67
+ "which brainframe-client",
68
+ "brainframe info",
69
+ "cat $(brainframe info install_path)/.env",
70
+ "cat $(brainframe info install_path)/docker-compose.yml",
71
+ "cat $(brainframe info install_path)/docker-compose.override.yml",
72
+ "ls -la $(brainframe info install_path)",
73
+ "ls -la $(brainframe info data_path)/capsules",
74
+ "docker container ls",
75
+ "curl http://localhost/api/version",
76
+ "curl http://localhost/api/license",
77
+ "curl http://localhost/api/plugins | python3 -mjson.tool",
78
+ "curl http://localhost/api/streams | python3 -mjson.tool",
79
+ "curl http://localhost/api/streams/status | python3 -mjson.tool",
80
+ "hostname -I",
81
+ "cat /proc/uptime",
82
+ "nslookup aotu.ai",
83
+ "cat /proc/uptime",
84
+ "ping aotu.ai -c 3",
85
+ "cat /proc/uptime",
86
+ "date",
87
+ "date -u",
88
+ ]
89
+
90
+
91
+ def _parse_args():
92
+ parser = ArgumentParser(
93
+ "This tool will print out the system and machine information and save to a file"
94
+ )
95
+ parser.add_argument(
96
+ "-f", "--file", default="sys.info", help="The output system info file name"
97
+ )
98
+ args = subcommand_parse_args(parser)
99
+
100
+ return args
101
+
102
+
103
+ def save_sys_info(log_filename):
104
+ file = open(log_filename, "w")
105
+
106
+ for line in header:
107
+ print(line)
108
+ file.writelines(line)
109
+
110
+ for line in cmdlines:
111
+
112
+ bf_info = "\n======== " + line + " ...\n"
113
+
114
+ print(bf_info)
115
+ file.writelines(str(bf_info))
116
+
117
+ if line.startswith("no curl"):
118
+ url = line.replace("no curl ", "")
119
+ session = requests.Session()
120
+ session.trust_env = False
121
+
122
+ response = session.get(url)
123
+ bf_info = json.dumps(response.json(), indent=2)
124
+
125
+ else:
126
+ sys_process = subprocess.Popen(
127
+ line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
128
+ )
129
+ bf_info = sys_process.stdout.read().decode("utf-8")
130
+
131
+ if len(bf_info) == 0:
132
+ bf_info = "None.\n"
133
+
134
+ print(bf_info)
135
+ # file.writelines(str(bf_info.encode('utf-8')))
136
+ file.writelines(str(bf_info))
137
+
138
+ for line in footer:
139
+ print(line)
140
+ file.writelines(line)
141
+
142
+ file.close()
143
+
144
+
145
+ @command("sys_info")
146
+ def sys_info():
147
+ args = _parse_args()
148
+
149
+ save_sys_info(args.file)
150
+
151
+ print(f"Saved in {args.file}")
152
+
153
+
154
+ if __name__ == "__main__":
155
+ by_name["sys_info"]()
@@ -0,0 +1,231 @@
1
+ #
2
+ # Copyright (c) 2021 Dilili Labs, Inc. All rights reserved. Contains Dilili Labs Proprietary Information. RESTRICTED COMPUTER SOFTWARE. LIMITED RIGHTS DATA.
3
+ #
4
+ import os
5
+ import subprocess
6
+ from argparse import ArgumentParser, RawTextHelpFormatter
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from subprocess import Popen
10
+ from time import sleep, time
11
+ from typing import Callable
12
+
13
+ from brainframe.api import BrainFrameAPI
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
17
+
18
+
19
+ class HeartBeat:
20
+ def __init__(self, log_path, interval, threshold):
21
+
22
+ self.interval = int(interval)
23
+ self.threshold = int(threshold)
24
+
25
+ if os.path.isdir(log_path) is not True:
26
+ print(f"{log_path} is invalid!")
27
+ return
28
+ self.log_path = log_path
29
+
30
+ self.time_0 = datetime.now()
31
+ self.log_path_prefix = None
32
+ self.heartbeat_log_file = None
33
+ self.brainframe_log_filename = None
34
+ self.heartbeat_log_open(interval, threshold)
35
+
36
+ def heartbeat_log_open(self, interval, threshold):
37
+ self.time_0 = datetime.now()
38
+ self.log_path_prefix = str(self.log_path) + f"/{self.time_0.isoformat()}_"
39
+ self.brainframe_log_filename = self.log_path_prefix + "brainframe.log"
40
+
41
+ log_filename = self.log_path_prefix + "brainframe_heartbeat.log"
42
+ self.heartbeat_log_file = Path(log_filename).resolve().open(mode="a")
43
+
44
+ self.heartbeat_log(
45
+ f"BrainFrame HeartBeat starts, interval = {interval}, threshold = {threshold}"
46
+ )
47
+
48
+ def heartbeat_log_close(self):
49
+ self.heartbeat_log(
50
+ f"BrainFrame HeartBeat session closed, {datetime.now() - self.time_0}"
51
+ )
52
+ self.heartbeat_log_file.close()
53
+
54
+ def heartbeat_log(self, log_str):
55
+ _log_str = f"[{datetime.now()}] " + str(log_str) + "\n"
56
+ print(_log_str)
57
+ self.heartbeat_log_file.writelines(_log_str)
58
+ self.heartbeat_log_file.flush()
59
+
60
+ def restart_brainframe(self):
61
+ 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)
65
+ self.stop_brainframe()
66
+ self.heartbeat_log(f"Save brainframe logs at {self.brainframe_log_filename}")
67
+ self.heartbeat_log_close()
68
+
69
+ self.heartbeat_log_open(self.interval, self.threshold)
70
+ self.heartbeat_log(f"Start brainframe")
71
+ self.start_brainframe()
72
+ self.heartbeat_log("brainframe has started")
73
+
74
+ def process_helper(self, cmd_str):
75
+ execution_start_time = datetime.now()
76
+ self.heartbeat_log(f"{cmd_str}: [{execution_start_time}]")
77
+ p = Popen(
78
+ cmd_str,
79
+ stdout=subprocess.PIPE,
80
+ stderr=subprocess.PIPE,
81
+ universal_newlines=True,
82
+ shell=True,
83
+ start_new_session=True,
84
+ close_fds=True,
85
+ )
86
+ # output = p.stdout.read()
87
+ output, err = p.communicate()
88
+ p.wait()
89
+ execution_complete_time = datetime.now()
90
+ self.heartbeat_log(f"{cmd_str} completed: [{execution_complete_time}]")
91
+
92
+ brainframe_log_file = (
93
+ Path(self.brainframe_log_filename).resolve().open(mode="a")
94
+ )
95
+ brainframe_log_file.writelines(f"[{execution_start_time}] {cmd_str}: stdout\n")
96
+ brainframe_log_file.writelines(output)
97
+ brainframe_log_file.writelines(f"[{execution_start_time}] {cmd_str}: stderr\n")
98
+ brainframe_log_file.writelines(err)
99
+ brainframe_log_file.writelines(f"[{execution_complete_time}] {cmd_str}\n")
100
+ brainframe_log_file.close()
101
+
102
+ self.heartbeat_log(f"Output are saved to {self.brainframe_log_filename}\n")
103
+
104
+ def save_brainframe_logs(self):
105
+ # os.system(f"brainframe compose logs &>> {log_filename}", )
106
+ cmd_str = ["brainframe compose logs"]
107
+ self.process_helper(cmd_str)
108
+
109
+ def stop_brainframe(self):
110
+ # os.system(f"brainframe compose down &>> {log_filename}")
111
+ cmd_str = ["brainframe compose down"]
112
+ self.process_helper(cmd_str)
113
+
114
+ def start_brainframe(self):
115
+ # os.system(f"brainframe compose up -d &>> {log_filename}")
116
+ cmd_str = ["brainframe compose up -d"]
117
+ self.process_helper(cmd_str)
118
+
119
+ def wait_for_heartbeat(self, fn: Callable, timeout: float = None):
120
+ """A helpful function to wait for heartbeat."""
121
+ heartbeat_val, heartbeat_response = None, None
122
+ start_time = time()
123
+ while timeout is None or time() - start_time < timeout:
124
+ try:
125
+ heartbeat_response = fn()
126
+ heartbeat_val = time() - start_time
127
+ break
128
+ except:
129
+ heartbeat_val = time() - start_time
130
+ break
131
+
132
+ return heartbeat_val, heartbeat_response
133
+
134
+ def heartbeat_monitor(self, api):
135
+ has_restarted = False
136
+ while True:
137
+ heartbeat_val, heartbeat_response = self.wait_for_heartbeat(
138
+ lambda: api.version(self.threshold), self.threshold
139
+ )
140
+ if heartbeat_response:
141
+ has_restarted = False
142
+ self.heartbeat_log(
143
+ f"version {heartbeat_response} heartbeat OK: response time - {heartbeat_val}"
144
+ )
145
+ else:
146
+ self.heartbeat_log(f"heartbeat failed: timeout - {heartbeat_val}")
147
+ if not has_restarted:
148
+ self.restart_brainframe()
149
+ has_restarted = True
150
+
151
+ sleep(self.interval)
152
+
153
+
154
+ def _parse_args():
155
+ parser = ArgumentParser(
156
+ description="This is the brainframe service monitor. Run the command with no arguments will launch"
157
+ " brainframe service and monitor the brainframe heartbeats. It will restart the service"
158
+ " when the heartbeats are not observed in the given timeout threshold. For example, run"
159
+ " the command below will monitor the heartbeats at an interval of 5 seconds. The command"
160
+ " will not launch brainframe automatically as '--start-now' is specified.\n\n"
161
+ " python brainframe_service_monitor.py --log-path ~/workspace --interval 2 --threshold 6 --start-now False\n\n"
162
+ "If the communication with brainframe fails, or a heartbeat deplay exceeds 6 seconds, the"
163
+ " service monitor will save the following log files in ~/workspace directory, then restart"
164
+ " the brainframe service,\n\n"
165
+ " <timestamp>_hearbeat.log\n"
166
+ " <timestamp>_brainframe.log\n"
167
+ " <timestamp>_sys.info\n\n"
168
+ "The default heartbeat interval and timeout threshold can be found in the arguments'"
169
+ " description.",
170
+ formatter_class=RawTextHelpFormatter,
171
+ )
172
+ parser.add_argument(
173
+ "--server-url",
174
+ default="http://localhost",
175
+ help="The URL for the BrainFrame server.",
176
+ )
177
+ parser.add_argument(
178
+ "--interval",
179
+ default=120,
180
+ help="The heartbeat checking interval. Default: %(default)i",
181
+ )
182
+ parser.add_argument(
183
+ "--threshold",
184
+ default=360,
185
+ help="The heartbeat timeout threshold. The service monitor will restart when the communication fails or timeout."
186
+ " Default: %(default)i",
187
+ )
188
+ parser.add_argument(
189
+ "--log-path",
190
+ type=Path,
191
+ default="./",
192
+ help="The logs will be saved in this path. Default: %(default)s",
193
+ )
194
+ parser.add_argument(
195
+ "--start-now",
196
+ default=True,
197
+ help="Start the brainframe service. Default: %(default)s",
198
+ )
199
+
200
+ args = subcommand_parse_args(parser)
201
+ return args
202
+
203
+
204
+ @command("service_monitor")
205
+ def service_monitor():
206
+ args = _parse_args()
207
+
208
+ # Connect to the BrainFrame Server
209
+ server_url = args.server_url
210
+
211
+ hb = HeartBeat(args.log_path, args.interval, args.threshold)
212
+
213
+ if args.start_now:
214
+ hb.start_brainframe()
215
+
216
+ hb.heartbeat_log(
217
+ f"heartbeat Connecting: BrainFrameAPI({server_url}), wait_for_server_initialization() ..."
218
+ )
219
+ api = BrainFrameAPI(server_url)
220
+ api.wait_for_server_initialization()
221
+
222
+ hb.heartbeat_log("heartbeat Connected")
223
+
224
+ hb.heartbeat_monitor(api)
225
+
226
+ hb.heartbeat_log("heartbeat exit")
227
+
228
+
229
+ if __name__ == "__main__":
230
+ by_name["service_monitor"]()
231
+