This repository has been archived by the owner on Apr 10, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.py
268 lines (243 loc) · 9.78 KB
/
app.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python
# coding: utf-8
import os
import sched
import json
import time
import datetime
import requests
import configparser
from tabulate import tabulate
from smtplib import SMTP
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.header import Header
TR_USE = ''
HEAVY_TR_USE = ''
HEAVY_ACCOUNTS = []
def get_resources(PRODUCER, account):
pars = {"account_name": account}
try:
data = requests.get(PRODUCER+"/v1/chain/get_account", json=pars)
except Exception as e:
print(e)
else:
return json.loads(data.text)
def get_values(raw):
if raw['account_name'] in HEAVY_ACCOUNTS:
try:
transactions = str(round((raw["ram_quota"]-raw["ram_usage"])/HEAVY_TR_USE))+" ("+str(HEAVY_TR_USE)+" bytes)"
except Exception as e:
print(e)
else:
try:
transactions = str(round((raw["ram_quota"]-raw["ram_usage"])/TR_USE))+" ("+str(TR_USE)+" bytes)"
except Exception as e:
print(e)
try:
net_perc = round((raw["net_limit"]["used"]/raw["net_limit"]["max"])*100)
except ZeroDivisionError:
net_perc = 0
try:
cpu_perc = round((raw["cpu_limit"]["used"]/raw["cpu_limit"]["max"])*100)
except ZeroDivisionError:
cpu_perc = 0
resource_obj = {
"account_name": raw["account_name"],
"ram_perc": round((raw["ram_usage"]/raw["ram_quota"])*100),
"ram_transactions": transactions,
"net_perc": net_perc,
"cpu_perc": cpu_perc,
}
return resource_obj
def display(resources):
os.system("clear")
headers = ['Account Name', 'RAM', 'NET', 'CPU', 'Transactions left (RAM bytes per transaction) approx.']
data = []
for account in resources:
data.append([
account["account_name"],
str(account['ram_perc'])+" %",
str(account['net_perc'])+" %",
str(account['cpu_perc'])+" %",
account['ram_transactions']
])
try:
table = tabulate(data, headers=headers, tablefmt='github')
except Exception as e:
print(e)
else:
print(table)
def mailer(data):
msg = MIMEMultipart('related')
msg['Subject'] = data['subject']
msg['To'] = data['to']
msg['Reply-to'] = '[email protected]'
msg.attach(data['message'])
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(data['MAIL_LOGIN'], data['MAIL_PASS'])
server.sendmail(from_addr=MAIL_LOGIN, to_addrs=msg['To'].split(','), msg=msg.as_string())
logging.info('Message sent: %s', msg['Subject'])
server.quit()
def notifyer(resources, MAIL_LOGIN, MAIL_PASS, RECIPIENTS, stats=False):
d = datetime.datetime.now()
if stats:
data = dict()
data['MAIL_LOGIN'] = MAIL_LOGIN
data['MAIL_PASS'] = MAIL_PASS
data['subject'] = 'DAILY ACCOUNT STATISTICS: ' + str(d.strftime("%B")) + ' ' + str(d.day)
data['to'] = RECIPIENTS
style = u'<!DOCTYPE html> \
<html> \
<head> \
<style> \
table, td, th {border: 1px solid #ddd;text-align: left;} \
table {border-collapse: collapse;width: 100%;} \
th, td {padding: 15px;} \
.date {background-color: #454545; text-align: center; width:20%; color:#e4e4e4} \
</style> \
</head> \
<body>'
table = u'<table>'
table += u'<tr><th>Account Name</th><th>RAM</th><th>NET</th><th>CPU</th><th>Transactions left (RAM bytes per transaction) approx.</th></tr>'
for account in resources:
table += u'<tr>'
table += u'<td>'+account['account_name']+u'</td>'
table += u'<td>'+str(account['ram_perc'])+u'%</td>'
table += u'<td>'+str(account['net_perc'])+u'%</td>'
table += u'<td>'+str(account['cpu_perc'])+u'%</td>'
table += u'<td>'+account['ram_transactions']+u'</td>'
table += u'</tr>'
table += u'</table><br>'
end = u'</body></html>'
html = style + u'<div>The daily account statistics.</div><br>' + \
table + u'<div class="date">' + str(d) + u'</div>' + end
data['message'] = MIMEText(html, 'html', 'utf-8')
mailer(data)
else:
data = dict()
data['MAIL_LOGIN'] = MAIL_LOGIN
data['MAIL_PASS'] = MAIL_PASS
data['subject'] = 'ACCOUNT RESOURCE ALERT'
data['to'] = RECIPIENTS
to_send = dict()
reasons = []
for account in resources:
if account['ram_perc']>=90 or int(account['ram_transactions'].split(' ')[0])<=30:
if account['account_name'] not in to_send.keys():
to_send[account['account_name']] = account
reasons.append('RAM percentage or Low amount of remaining transactions.')
if account['net_perc']>= 90:
if account['account_name'] not in to_send.keys():
to_send[account['account_name']] = account
reasons.append('NET percentage.')
if account['cpu_perc']>= 90:
if account['account_name'] not in to_send.keys():
to_send[account['account_name']] = account
reasons.append('CPU percentage.')
if to_send:
style = u'<!DOCTYPE html> \
<html> \
<head> \
<style> \
table, td, th {border: 1px solid #ddd;text-align: left;} \
table {border-collapse: collapse;width: 100%;} \
th, td {padding: 15px;} \
th {background-color:#983628; color:#e4e4e4} \
td {background-color: #F15152} \
.date {background-color: #454545; text-align: center; width:20%; color:#e4e4e4} \
</style> \
</head> \
<body>'
table = u'<table>'
table += u'<tr><th>Account Name</th><th>RAM</th><th>NET</th><th>CPU</th><th>Transactions left (RAM bytes per transaction) approx.</th></tr>'
for value in to_send.values():
table += u'<tr>'
table += u'<td>'+value['account_name']+u'</td>'
table += u'<td>'+str(value['ram_perc'])+u'%</td>'
table += u'<td>'+str(value['net_perc'])+u'%</td>'
table += u'<td>'+str(value['cpu_perc'])+u'%</td>'
table += u'<td>'+value['ram_transactions']+u'</td>'
table += u'</tr>'
table += u'</table><br>'
end = u'</body></html>'
if reasons:
reason = u'<div class="reason">'
for x in reasons:
reason += u'<p>' + x + u'</p>'
reason += u'</div><br>'
html = style + u'<div>Some account seems to run out of resources.</div><br>' + \
reason + \
table + u'<div class="date">' + str(d) + u'</div>' + end
data['message'] = MIMEText(html, 'html', 'utf-8')
logging.info('Alert: %s', to_send)
mailer(data)
else:
logging.info('No alerts')
def tester(PRODUCER, ACCOUNTS, MAIL_LOGIN, MAIL_PASS, RECIPIENTS, stats=False):
logging.debug('Run checks.')
resources = []
for account in ACCOUNTS:
raw = get_resources(PRODUCER, account)
resources.append(get_values(raw))
if not stats:
display(resources)
notifyer(resources, MAIL_LOGIN, MAIL_PASS, RECIPIENTS)
else:
notifyer(resources, MAIL_LOGIN, MAIL_PASS, RECIPIENTS, stats)
if __name__ == "__main__":
try:
logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',
filename='eosaccountmonitor.log',
level=logging.DEBUG,
datefmt='%m/%d/%Y %I:%M:%S %p')
except Exception as e:
print(e)
else:
logging.info('Launch the app.')
config = configparser.ConfigParser()
delayer = sched.scheduler(time.time, time.sleep)
try:
config.read('config')
logging.info('Config reading.')
except Exception as e:
logging.error('Could not read the config: %s', e)
print(e)
else:
default = config['DEFAULT']
TIMEOUT = int(default.get('TIMEOUT')) or 1
STATS_TIMEOUT = int(default.get('STATS_TIMEOUT')) or 24
PRODUCER = default.get('PRODUCER') or 'https://eos.greymass.com'
ACCOUNTS = default.get('ACCOUNTS').split(',') or ['eosio.token']
MAIL_LOGIN = default.get('MAIL_LOGIN') or ''
MAIL_PASS = default.get('MAIL_PASS') or ''
RECIPIENTS = default.get('RECIPIENTS') or '[email protected]'
TR_USE = int(default.get('TR_USE')) or 160
HEAVY_TR_USE = int(default.get('HEAVY_TR_USE')) or 500
HEAVY_ACCOUNTS = default.get('HEAVY_ACCOUNTS').split(',') or []
def run_task():
try:
tester(PRODUCER, ACCOUNTS, MAIL_LOGIN, MAIL_PASS, RECIPIENTS)
finally:
delayer.enter(TIMEOUT*3600, 1, run_task)
run_task()
def run_stats():
try:
tester(PRODUCER, ACCOUNTS, MAIL_LOGIN, MAIL_PASS, RECIPIENTS, stats=True)
finally:
delayer.enter(STATS_TIMEOUT*3600, 1, run_stats)
run_stats()
try:
delayer.run()
logging.info('Run scheduler.')
except KeyboardInterrupt:
logging.info('Exit the app. Keyboard interruption.')
print('\nKeyboard interruption. \nExit.')
except Exception as e:
logging.error('Exit by other reason: %s', e)
print(e)