-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebMonitor.py
More file actions
311 lines (258 loc) · 9.11 KB
/
WebMonitor.py
File metadata and controls
311 lines (258 loc) · 9.11 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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import os
import json
import urllib.error
import urllib.request
from urllib.error import URLError
from time import strftime
from columnar import columnar
# Console color codes
WHITE = '\033[00m'
GREEN = '\033[0;92m'
RED = '\033[1;31m'
class WebMonitor:
def __init__(self, pcf='WebMonitor'):
self.__ext = '.pcf'
self.__cfg = f'{pcf}'
self.__storage = f'{pcf}{self.__ext}'
if not os.path.exists(self.__storage):
data_model = {
self.__cfg: {
'added_hosts': [],
'history': []
}
}
self._save(data_model)
# @ Add hosts to configuration file
# Args:
# - hosts: tuple or list
# > supported types:
# - tuple: add('example.com', etc.)
# - list: add(['example.com', etc.])
# @ return: list(added_hosts)
def add(self, *hosts):
if len(hosts) == 0:
raise ValueError('Arguments has not exist.')
# get data
data = self._pull()
hosts = self._format_input_types(hosts)
# append added host to data
for host in hosts:
data[self.__cfg]['added_hosts'].append(host)
# remove duplicates
data[self.__cfg]['added_hosts'] = list(set(data[self.__cfg]['added_hosts']))
# sort data
data[self.__cfg]['added_hosts'].sort()
# and save
self._save(data)
return data[self.__cfg]['added_hosts']
# @ Remove hosts from configuration file
# Args:
# - hosts: tuple or list
# > supported types:
# - tuple: remove('example.com', etc.)
# - list: remove(['example.com', etc.])
# @ return: list(added_hosts)
def remove(self, *hosts):
if len(hosts) > 0:
hosts = self._format_input_types(hosts)
data = self._pull()
# response user if not list hosts
if len(hosts) == 0:
response = input(f"Are you sure you want to clear the host list? [Y/n]\n > ")
if len(response) == 0 or response == "":
response = 'Y'
if response == 'Y':
print("You host list is cleared.")
data[self.__cfg]['added_hosts'].clear()
self._save(data)
return
else:
print('Clearing the list has been canceled.')
for arg in hosts:
data[self.__cfg]['added_hosts'] = list(filter(lambda a: a != arg, data[self.__cfg]['added_hosts']))
# sort data
# TODO: don't use (?)
# > comment: sorted when call add()
# data[self.__cfg]['added_hosts'].sort()
# and save
self._save(data)
return data[self.__cfg]['added_hosts']
# @ Checks hosts from configuration file
# Args:
# - hosts: tuple or list
# > supported types:
# - tuple: check('example.com', etc.)
# - list: check(['example.com', etc.])
# @ return: list(added_hosts)
def check(self, *hosts):
if len(hosts) > 0:
hosts = self._format_input_types(hosts)
data = self._pull()
if len(hosts) == 0:
hosts = data[self.__cfg]['added_hosts']
try:
if len(data[self.__cfg]['history']) == 0:
pass
except KeyError:
data[self.__cfg]['history'] = []
cli_output = []
print('Please, wait report ...')
for host in hosts:
print('Checking', host.strip(), '...')
host = 'http://' + host.strip()
status_code = 0
try:
urllib.request.urlopen(host)
status = 'available'
status_code = 1
color = GREEN
except URLError:
status = 'сonnection error'
color = RED
except:
status = 'failed to check'
color = RED
history = {
'id': int(len(data[self.__cfg]['history']) + 1),
'date': strftime("%Y.%m.%d"),
'time': strftime("%T"),
'host': str(host),
'status': str(status),
'status_code': int(status_code),
}
data[self.__cfg]['history'].append(history)
current_time = f'{history["date"]} {history["time"]}'
signal = f'{color}•{WHITE}'
status = f'{color}{status}{WHITE}'
cli_output.append([
'{:^24}'.format(current_time),
'{:^32}'.format(f'{signal} {host}'),
'{:^18}'.format(status)
])
# Out to Cli
headers = [
'{:^24}'.format('time'),
'{:^32}'.format('host'),
'{:^18}'.format('status'),
]
table = columnar(cli_output, headers, no_borders=True, justify='c', terminal_width=600)
# Save history
self._save(data)
return table
# @ Show added hosts to PCF
# Print to Cli in realtime
# @ return list(hosts)
def show(self):
data = self._pull()
hosts = data[self.__cfg]["added_hosts"]
for host in hosts:
print(host)
return hosts
# @ Show check history
# Args:
# - clear: clear history
# - by: show history by [id, date, host, status_code]
# How use by arg: [{filed: value}, *multiply]
# Example: [{'id': 10}, *multiply]
# @ return table
def history(self, clear=False, by=None):
data = self._pull()
histories = data[self.__cfg]['history']
if len(histories) == 0:
print('History is empty.')
return
if clear is True:
response = input(f"Are you sure you want to clear history? [Y/n]\n > ")
if len(response) == 0 or response == "":
response = 'Y'
if response == 'Y':
print("You history is cleared.")
data[self.__cfg]['history'].clear()
self._save(data)
else:
print('Clearing history has been canceled.')
self.history()
return
cli_output = []
if by is not None:
histories = self._filter_history(histories, by)
for history in histories:
color = GREEN
if history['status_code'] == 0:
color = RED
current_time = f'{history["date"]} {history["time"]}'
signal = f'{color}•{WHITE}'
status = f'{color}{history["status"]}{WHITE}'
cli_output.append([
'{:^6}'.format(history["id"]),
'{:^24}'.format(current_time),
'{:50}'.format(f'{signal} {history["host"]}'),
'{:^18}'.format(status)
])
headers = [
'{:^6}'.format('id'),
'{:^24}'.format('time'),
'{:^30}'.format('host'),
'{:^18}'.format('status')
]
table = columnar(cli_output, headers, no_borders=True, justify='c', terminal_width=600)
return table
# @ private method
# Save data to configuration
# Args:
# - data: data
# @ return None
def _save(self, data):
with open(self.__storage, "w") as write_file:
json.dump(data, write_file)
# @ private method
# Load data from configuration
# Args:
# - data: data
# @ return dict(data)
def _pull(self):
with open(self.__storage, "r") as content:
return json.loads(content.read())
@staticmethod
# Prepend data as list
# Args:
# - data: data
# @ return list(data)
def _format_input_types(data):
if len(data) == 0:
raise ValueError('Missing data to format.')
# set `hosts` as list
data = list(data)
# if exist inner list\
# unpack items
if type(data[0]) is list:
data = data[0]
return data
@staticmethod
# Filtering history
# Args:
# - histories: input histories data
# - conditions: input conditions as dict
# @ return list(data)
def _filter_history(histories, conditions):
if conditions is not None:
filter_histories = []
for history in histories:
for condition in conditions:
for field, value in condition.items():
# print(f'field {field} with {value}')
allowedFields = ['id', 'date', 'host', 'status_code']
if field not in allowedFields:
raise KeyError(f'This ORDER BY `{field}` not allowed.')
if field in history:
if field == 'id' and type(value) == list:
for val in value:
if history[field] == int(val):
filter_histories.append(history)
if field == 'host':
value = 'http://' + value
if history[field] == value:
filter_histories.append(history)
return filter_histories
else:
return histories