-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
343 lines (294 loc) · 13.8 KB
/
core.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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#!/usr/bin/python3
#
# written by @author ZyzonixDev
# published by ZyzonixDevelopments
# -
# date | 18/03/2021
# python-v | 3.5.3
# -
# file | core.py
# project | MontSy
# project-v | 0.9.6
#
from datetime import date, datetime
from configparser import ConfigParser
import os
import sys
import openpyxl
import time
from static.values import colorsetting as color
# writing console output to console and logfile
class LogWriter(object):
def __init__(self, *files):
# retrieving files / output locations
self.files = files
def write(self, obj):
# getting files (logfile / console (as file))
for file in self.files:
file.write(obj)
file.flush()
def flush(self):
# flushing written lines/files
for file in self.files:
file.flush()
# software functionalities (sov and mon)
class Handlers(object):
# system overview handler | key: s
def handleOverview(self):
from modules import overview
from static import values
output = overview.prepareStoring(self)
module_list = overview.retrieveModules(self)
try:
for key in module_list:
data = module_list[key]()
# checking if function returns nothing
if not data:
print(self.getTime(), "empty - " + key)
else:
print(self.getTime(), "writing data - " + key)
output.write(values.sov_headers[key])
for dictio in data:
d_keys = dictio.keys()
for d_key in d_keys:
# kicking values if they're empty
if dictio[d_key]:
output.write("\n" + d_key + " " + str(dictio[d_key]))
print(self.getTime(), color.GREEN + "created system overview successfully\n" + color.END)
output.close()
except Exception as e:
print(e)
print(self.getTime(), color.RED + "something went wrong - wasn't able to create a system overview" + color.END)
# system monitoring handler | key: m
def handleMonitoring(self, files, modules, net_modules):
from modules import monitoring
import sqlite3, threading
# modules = dict[number : modulename]
print(self.getTime(), "collecting data and writing to files")
connectionArray = {}
xlsxfile = ""
for file in files:
if file.endswith(".db"):
connection = sqlite3.connect(file)
connectionArray["sqlite"] = connection
elif file.endswith(".xlsx"):
workbook = openpyxl.load_workbook(file)
connectionArray["xlsx"] = workbook
xlsxfile = file
try:
data = {}
net_data = {}
cmd = ""
net_cmd = ""
if modules:
cmd += "'" + str(monitoring.getDate()) + "', '" + str(monitoring.getTime()) + "'"
counter = 1
for module in modules:
sdata = modules[module]()
for key in sdata:
selected_data = sdata[key]
for smod in selected_data:
data[counter] = selected_data[smod]
cmd += ", " + str(selected_data[smod])
counter += 1
if net_modules:
net_cmd += "'" + str(monitoring.getDate()) + "', '" + str(monitoring.getTime()) + "'"
counter = 1
for net_module in net_modules:
sdata = net_modules[net_module]()
for key in sdata:
selected_data = sdata[key]
for smod in selected_data:
net_data[counter] = selected_data[smod]
net_cmd += ", '" + str(selected_data[smod]) + "'"
counter += 1
for connectionKey in connectionArray.keys():
if connectionKey == "sqlite":
connection = connectionArray[connectionKey]
dbCursor = connection.cursor()
if cmd != "":
#print(cmd)
dbCursor.execute("INSERT INTO General VALUES (" + cmd + ")")
if net_cmd != "":
#print(net_cmd)
dbCursor.execute("INSERT INTO Network VALUES (" + net_cmd + ")")
connection.commit()
connection.close()
elif connectionKey == "xlsx":
workbook = connectionArray[connectionKey]
if cmd != "":
worksheet = workbook.get_sheet_by_name("General")
row = workbook.active.max_row + 1
data_list = []
data_list.append(monitoring.getDate())
data_list.append(monitoring.getTime())
for key in data.keys():
data_list.append(data[key])
for column, item in enumerate(data_list, start=1):
worksheet.cell(row, column, item)
if net_cmd != "":
worksheet = workbook.get_sheet_by_name("Network")
row = workbook.active.max_row + 1
data_list = []
data_list.append(monitoring.getDate())
data_list.append(monitoring.getTime())
for key in net_data.keys():
data_list.append(net_data[key])
for column, item in enumerate(data_list, start=1):
worksheet.cell(row, column, item)
workbook.save(filename=xlsxfile)
workbook.close()
# scheduling next run
threading.Timer(self.MES_TIME, Handlers.handleMonitoring, [self, files, modules, net_modules]).start()
except KeyboardInterrupt as e:
print(e)
print(self.getTime(), color.RED + "stopped MontSy" + color.END)
# system monitoring handler (preparation) | key: m
def prepareMonitoring(self):
from modules import monitoring
from static import values
module_list = self.enabled_module_list["m"]
# general: everything except network
sheetNeeded = {
"generalmonitoring" : False,
"networkmonitoring" : False
}
keys = sheetNeeded.keys()
mod_keys = module_list.keys()
for key in mod_keys:
selected_module = module_list[key]
if selected_module.startswith("net_"):
sheetNeeded["networkmonitoring"] = True
else:
sheetNeeded["generalmonitoring"] = True
fileName = str(date.today()) + "_" + str(datetime.now().strftime("%H-%M-%S"))
files = []
fileTypes = values.storageMethod[self.storage_m]
for type in fileTypes:
files.append(fileName + type)
# returns created files (not path/name)
prepTableNames = list(keys)
for key in prepTableNames:
if not sheetNeeded[key]:
prepTableNames.remove(key)
# collecting and summing up required data
modules, net_modules = monitoring.retrieveModules(self)
fileArray = monitoring.createStorage(self, files, prepTableNames, modules, net_modules)
if not fileArray: return
Handlers.handleMonitoring(self, fileArray, modules, net_modules)
# core class (__init__ initializes the system)
class Core(object):
# console time service
def getTime(self):
curTime = "[" + str(datetime.now().strftime("%H:%M:%S")) + "]"
return curTime
# getting configuration from config file
def getModConfig(self, configImport, importModules):
modulespec = self.static[importModules]
modulelist = {}
try:
print(self.getTime(), "getting configuration for '" + modulespec[importModules] + "'")
modulesToImport = configImport[modulespec["config"]]
if modulesToImport:
counter = 1
for module in modulesToImport:
# selecting all modules where the value == True (boolean not string)
selected_module = configImport.getboolean(modulespec["config"], module)
if selected_module == True:
modulelist[counter] = module
print(self.getTime(), "moduleinfo (" + modulespec[importModules] + ") - enabled - installed:", module)
else:
print(self.getTime(), "moduleinfo (" + modulespec[importModules] + ") - disabled:", module)
counter += 1
time.sleep(0.1)
else:
print(self.getTime(),"no modules found - check config file")
return False
# saving collected modules to list
self.enabled_module_list[importModules] = modulelist
if not modulelist: return False
print(self.getTime(), color.GREEN + "reading " + modulespec[importModules] + "-configuration passed\n" + color.END)
return True
except Exception as e:
print(self.getTime(), color.RED + "something went wrong - was not able to get the configuration - exiting...\n" + color.END)
print(e)
return False
# writing console to log
def writeLog(self):
self.logFile = open(os.getcwd() + "/logs/" + str(date.today()) + "_" + str(
datetime.now().strftime("%H-%M-%S")) + "_log.txt", "w")
sys.stdout
sys.stdout = LogWriter(sys.stdout, self.logFile)
def __init__(self):
# saving ressources global (like public) // retrieving missing from config file
configImport = ConfigParser()
configFile = os.getcwd() + "/static/config.ini"
# os.getcwd() returns execution directory
configImport.read(configFile)
# preparing instance for saving execution directory
configWriter = ConfigParser(comment_prefixes='/', allow_no_value=True)
configWriter.read(configFile)
try:
# importing config data
self.baseFilePath = os.getcwd() + "/"
configWriter["CONFIGURATION"]["basefilepath"] = self.baseFilePath
# writing execution directory to file
with open(configFile, "w") as file:
configWriter.write(file)
self.MES_TIME = int(configImport["CONFIGURATION"]["log_dur"])
self.storage_m = int(configImport["CONFIGURATION"]["mon_storage_method"])
self.out_directory = configImport["CONFIGURATION"]["output_dest"]
except Exception as e:
print(e)
return
# initializing log, if enabled
if int(configImport["CONFIGURATION"]["log_enabled"]) == 1:
self.writeLog()
from static import values
# preparing lists for enabled modules
self.enabled_module_list = values.module_dictionary
# importing preset settings
self.static = values.static
# starting software
print(self.getTime(), "reading arguments (" + str(len(sys.argv)) + ")")
# if a valid argument is given --> selected method will be executed
if len(sys.argv) != 1:
prov_arg = sys.argv[1]
if not prov_arg in self.static.keys():
print(self.getTime(), "wrong argument provided (" + prov_arg + ") - exiting...\n")
return
print(self.getTime(), self.static[prov_arg]["console"])
# importing modules (checking config for en- and disabled modules)
if self.getModConfig(configImport, prov_arg) == False:
print(self.getTime(), color.RED + "all modules are disabled - exiting... " + color.END)
return
# starting selected module
if prov_arg == "s":
Handlers.handleOverview(self),
elif prov_arg == "m":
Handlers.prepareMonitoring(self)
# if no argument provided: systemooverview will run first, then initializing the monitoring part
else:
# getting configuration for both possibilities
getModules = "all"
getAll = ["s","m"]
check = []
print(self.getTime(), self.static[getModules][getModules])
for method in getAll:
if self.getModConfig(configImport, method) == False:
print(self.getTime(), color.RED + "all modules for method '" + self.static[method][method] + "' are disabled" + color.END)
check.append("PLACEHOLDER")
if len(check) == 2:
print(self.getTime(), color.RED + "all modules are disabled - please change the config file (static/config.ini) - exiting..." + color.END)
return
# prints module list
#print(self.enabled_module_list[method])
print(self.getTime(), "starting to create a system overview")
# func for sov-handling here
Handlers.handleOverview(self)
print(self.getTime(), "installing system monitoring")
# func for mon-handling here
Handlers.prepareMonitoring(self)
# initializes the core system
if __name__ == "__main__":
Core()