-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport_usage_winservice.py
174 lines (142 loc) · 5.71 KB
/
report_usage_winservice.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import time
import json
import traceback
from datetime import datetime
import threading
import sys
from influxdb import InfluxDBClient
import psutil
import argparse
import GPUtil
import setproctitle
import win32serviceutil
import win32service
import win32event
import servicemanager
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "HWMonitor"
_svc_display_name_ = "InfluxDB HWMonitor"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.nickname = '5700G+3060'
self.previous_net = None
self.interval = 3
self.disk_list = [
'c:',
'd:',
'e:',
]
self.is_running = True
self.dbclient = None
def SvcStop(self):
self.is_running = False
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.is_running = True
self.main()
def gen_hw_usage(self):
time.sleep(self.interval)
res = {}
res['cpu'] = psutil.cpu_percent(percpu=True)
res['cpu_total'] = psutil.cpu_percent()
res['ram'] = psutil.virtual_memory()._asdict()
def gen_disk_usage(disk):
d = psutil.disk_usage(disk)
return {'id': disk, 'total': d.total, 'used': d.used, 'free': d.free, 'percent': d.percent}
res['disk'] = [gen_disk_usage(i) for i in self.disk_list]
current_net = psutil.net_io_counters(pernic=True)
if_info = psutil.net_if_stats()
res['net'] = []
for if_stat in if_info:
if if_info[if_stat].speed > 0:
res['net'].append({
'id': if_stat,
'bandwidth': if_info[if_stat].speed, # Mbps
'recv_bytes_ps': (current_net[if_stat].bytes_recv - self.previous_net[if_stat].bytes_recv) * 8 / self.interval if self.previous_net is not None else 0, # bps
'sent_bytes_ps': (current_net[if_stat].bytes_sent - self.previous_net[if_stat].bytes_sent) * 8 / self.interval if self.previous_net is not None else 0 # bps
})
self.previous_net = current_net
try:
res['gpu'] = [{'id': gpu.id, 'load': gpu.load, 'mem_used': gpu.memoryUsed, 'mem_total': gpu.memoryTotal, 'mem_util': gpu.memoryUtil} for gpu in GPUtil.getGPUs()]
except:
res['gpu'] = []
return res
# single worker
def fetch_hw_info(self):
nickname = self.nickname
def parse_info_to_json(r):
info = r
ts = datetime.utcnow().isoformat()
def get_common_body(measurement, name, fields):
return {
"measurement": measurement,
"tags": {
"host": nickname,
measurement: name
},
"time": ts,
"fields": fields
}
cpu_body = [get_common_body("cpu", f"cpu{i:d}", {"value": j}) for i, j in enumerate(info['cpu'])]
cpu_body.append(get_common_body("cpu", f"cpu-total", {"value": info['cpu_total']}))
ram_body = [{
"measurement": "ram",
"tags": {
"host": nickname
},
"time": ts,
"fields": info['ram']
}]
def parse_gpu(js):
js['mem_available'] = js['mem_total'] - js['mem_used']
del js['id']
return js
def parse_net(js):
js['recv_bytes_ps'] = float(js['recv_bytes_ps'])
js['sent_bytes_ps'] = float(js['sent_bytes_ps'])
del js['id']
return js
def parse_disk(js):
js['free'] = int(js['free'])
js['total'] = int(js['total'])
js['used'] = int(js['used'])
js['percent']= float(js['percent'])
del js['id']
return js
net_body = [get_common_body("net", net['id'], parse_net(net)) for net in info['net']]
if 'disk' in info:
disk_body = [get_common_body("disk", d['id'], parse_disk(d)) for d in info['disk']]
else:
disk_body = []
if 'gpu' in info:
gpu_body = [get_common_body("gpu", f"gpu{j['id']}", parse_gpu(j)) for j in info['gpu']]
else:
gpu_body = []
return cpu_body + ram_body + gpu_body + net_body + disk_body
while self.is_running:
try:
r = self.gen_hw_usage()
points = parse_info_to_json(r)
self.dbclient.write_points(points, time_precision='ms')
except:
print(f"Server: {nickname}:")
traceback.print_exc()
print('*' * 8)
break
def main(self):
retry_delay = 15
while self.is_running:
try:
self.dbclient = InfluxDBClient('localhost', 8086, 'python', 'python&input', 'monitor')
self.fetch_hw_info()
self.dbclient.close()
except:
print(f"[{self.nickname}]: Found some error, try again after {retry_delay}s", file=sys.stderr)
traceback.print_exc()
time.sleep(retry_delay)
self.dbclient.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)