schedule.py
7.8 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
# import schedule
import os
import paramiko
from .models import MonitorHost, MonitorLog
import datetime
import math
import time
import uuid
import schedule
from app.util.component.RunContinuous import run_continuously
from app.util.component.PGUtil import PGUtil
import configure
def background_job():
try:
# print('Hello from the background thread')
# base_dir = os.getcwd()
# 命令文件
# cmd_filepath = os.path.join(base_dir, "file", "monitor.txt")
# cmd_file = open(cmd_filepath, "r")
# cmd = cmd_file.read()
# cmd_file.close()
# servers = [{'sid': 'src1', 'hostname': '172.26.99.160',
# 'username': 'monitor', 'password': '123456'},
# {'sid': 'src2', 'hostname': '172.26.60.100',
# 'username': 'root', 'password': 'DMap@123'}]
cur_time = datetime.datetime.now()
time_stamp = cur_time.strftime(
"%Y-%m-%d %H:%M:%S")
struct_time = time.strptime(time_stamp, "%Y-%m-%d %H:%M:%S")
d_minu_stamp = math.floor(struct_time.tm_min/10)
f_minu_stamp = math.floor(struct_time.tm_min/5)
sys_session = PGUtil.get_db_session(
configure.SQLALCHEMY_DATABASE_URI)
sys_ds = PGUtil.open_pg_data_source(
0, configure.SQLALCHEMY_DATABASE_URI)
hosts = sys_session.query(
MonitorHost.host, MonitorHost.user, MonitorHost.password, MonitorHost.type, MonitorHost.srcid)
servers = list(map(lambda host:
{'hostname': host.host, 'username': host.user,
'password': host.password, 'type': host.type,
'sid': host.srcid},
hosts))
for info in servers:
try:
# 业务逻辑
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname=info['hostname'],
username=info['username'], password=info['password'])
# cpu
order = "top -b -n1 | sed -n '3p' | awk '{print $2}'"
stdin, stdout, stderr = client.exec_command(order)
cpu_usage = stdout.read().decode().split("\n")[0] # cpu使用率
# 内存
order = "free -m | sed -n '2p' | awk '{print $2}'"
stdin, stdout, stderr = client.exec_command(order)
totalMem = stdout.read().decode().split("\n")[0] # 总内存
order = "free -m | sed -n '2p' | awk '{print $7}'"
stdin, stdout, stderr = client.exec_command(order)
availableMem = stdout.read().decode().split("\n")[0] # 可用内存
order = "free -m | sed -n '2p' | awk '{print $3}'"
stdin, stdout, stderr = client.exec_command(order)
usedMem = stdout.read().decode().split("\n")[0] # 已用内存
# disk
order = "df -m | grep -v 'overlay\|Filesystem' | awk '{print $1,$2,$3}' | grep /dev | awk '{print $2}' | awk -v total=0 '{total+=$1}END{print total}'"
stdin, stdout, stderr = client.exec_command(order)
totalDisk = int(stdout.read().decode().split("\n")
[0]) # 总磁盘空间,单位Mb
order = "df -m | grep -v 'overlay\|Filesystem' | awk '{print $1,$2,$3}' | grep /dev | awk '{print $3}' | awk -v total=0 '{total+=$1}END{print total}'"
stdin, stdout, stderr = client.exec_command(order)
usedDisk = int(stdout.read().decode().split("\n")
[0]) # 已使用磁盘空间,单位Mb
# network
# 接收的字节数
rx_time = []
rx_bytes = []
tx_time = []
tx_bytes = []
# 接收的字节数
order = "ifconfig | grep RX | grep -v 'errors'| awk -v total=0 '{total+=$5}END{print total}'"
i = 0
while i < 2:
i = i+1
stdin, stdout, stderr = client.exec_command(order)
rx_time.append(time.time())
rx_bytes.append(int(stdout.read().decode().split("\n")[0]))
# 发送的字节数
order = "ifconfig | grep TX | grep -v 'errors'| awk -v total=0 '{total+=$5}END{print total}'"
i = 0
while i < 2:
i = i+1
stdin, stdout, stderr = client.exec_command(order)
tx_time.append(time.time())
tx_bytes.append(int(stdout.read().decode().split("\n")[0]))
log_guid = uuid.uuid1().__str__()
monitor_log = MonitorLog(guid=log_guid,
server=info["hostname"],
time_stamp=cur_time,
cpu_usage=float(
"%.2f" % float(cpu_usage)),
total_mem=totalMem,
available_mem=availableMem,
used_mem=usedMem,
disk=totalDisk,
disk_usage=usedDisk,
net_recv=float("%.2f" % float((
rx_bytes[1] - rx_bytes[0])/(rx_time[1]-rx_time[0]))),
net_send=float("%.2f" % float((
tx_bytes[1] - tx_bytes[0])/(tx_time[1]-tx_time[0]))),
date_stamp=cur_time.strftime(
"%Y-%m-%d"),
hour_stamp=struct_time.tm_hour,
minu_stamp=struct_time.tm_min,
d_minu_stamp=1 if d_minu_stamp == 0 else d_minu_stamp,
f_minu_stamp=1 if f_minu_stamp == 0 else f_minu_stamp)
sys_session.add(monitor_log)
sys_session.commit()
# for line in stdout:
# data = json.loads(line)
# # print(type(data))
# print(data)
except Exception as e:
sys_session.rollback()
except e:
print('发生了异常:', e)
finally:
client.close()
if sys_session:
sys_session.close()
if sys_ds:
sys_ds.Destroy()
# 记录30条记录
logs = []
def start_schedule():
# # 1分钟巡检一次
schedule.every(2).minutes.do(background_job)
# schedule.every(5).seconds.do(background_job)
stop_run_continuously = run_continuously()
# Do some other things...
# # Stop the background thread
# time.sleep(10)
# stop_run_continuously.set()
def format_value(value):
# 1024*1024*1024
if value > 1_073_741_824:
value = "{}GB".format(format(value/1_073_741_824, '.1f'))
elif value > 1_048_576:
# 1024*1024
value = "{}MB".format(format(value / 1_048_576, '.1f'))
elif value > 1024:
value = "{}KB".format(format(value / 1024.0, '.1f'))
else:
value = "{}B".format(format(value, '.1f'))
return value
def Mb_format_value(value):
if value > 1024:
value = "{}GB".format(format(value/1024, '.1f'))
else:
value = "{}MB".format(format(value, '.1f'))
return value