This repository has been archived by the owner on Apr 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Anatomize.py
213 lines (166 loc) · 8.16 KB
/
Anatomize.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
#!/usr/bin/python3
"""
Anatomize.py
APP: Inquisition
DESC: A library for reading in and parsing log files based on templates
CREATION_DATE: 2017-04-08
"""
# MODULES
# | Native
import logging
from os import fork
from time import sleep
# | Third-Party
import pymysql
import redis
# | Custom
from lib.anatomize.Parser import Parser
# METADATA
__author__ = 'Joshua Carlson-Purcell'
__copyright__ = 'Copyright 2017, CarlsoNet'
__license__ = 'MIT'
__version__ = '1.0.0-alpha'
__maintainer__ = 'Joshua Carlson-Purcell'
__email__ = 'jcarlson@carlso.net'
__status__ = 'Development'
class Anatomize:
"""
Anatomize.py is a class used for reading in and parsing log files based on given field templates
"""
lgr = None
cfg = {}
inquisitionDbHandle = None
logDbHandle = None
parserStore = {}
def __init__(self, cfg):
self.cfg = cfg
# start logger
self.lgr = self.generateLogger()
self.lgr.info('starting Anatomize engine...')
# create db handle for log database
# NOTE: StrictRedis won't actually raise an exception if we can't connect; only when we run queries
# go figure -_-
self.logDbHandle = redis.StrictRedis(host=cfg['log_database']['host'], port=cfg['log_database']['port'])
self.lgr.debug('database connection established for log database :: [ ' + cfg['log_database']['host']
+ ':' + cfg['log_database']['port'] + ' ]')
# create connection to inquisition db
try:
self.inquisitionDbHandle = self.generateInquisitionDbConnection(cfg['mysql_database']['db_user'],
cfg['mysql_database']['db_pass'],
cfg['mysql_database']['db_name'],
cfg['mysql_database']['db_host'],
int(cfg['mysql_database']['db_port']))
self.lgr.debug('database connection established for main inquisition database :: [ '
+ cfg['mysql_database']['db_host'] + ':' + cfg['mysql_database']['db_port'] + ' ]')
self.lgr.info('all database connections established [ SUCCESSFULLY ]')
# load parsers and associated templates (IN PROGRESS)
self.parserStore = self.fetchParsers()
self.lgr.debug('loaded [ ' + str(len(self.parserStore)) + ' ] parsers into parser store')
except (pymysql.InternalError, pymysql.ProgrammingError) as e:
self.lgr.critical('could not fetch parsers from inquisition database :: [ ' + str(e) + ' ]')
exit(2)
except pymysql.OperationalError as e:
self.lgr.critical('could not create database connection :: [ ' + str(e) + ' ]')
exit(2)
def generateLogger(self):
"""
Generate logging handler with given info
:return: logger
"""
# initialize logger
newLgr = logging.getLogger(__name__)
# set logging level
logLvl = getattr(logging, self.cfg['logging']['logLvl'].upper())
newLgr.setLevel(logLvl)
# create file handler for log file
fileHandler = logging.FileHandler(self.cfg['logging']['logFile'])
fileHandler.setLevel(logLvl)
# set output formatter
# NOTE: we need to get the logFormat val with the raw flag set in order to avoid logging from interpolating
frmtr = logging.Formatter(self.cfg.get('logging', 'logFormat', raw=True))
fileHandler.setFormatter(frmtr)
# associate file handler w/ logger
newLgr.addHandler(fileHandler)
return newLgr
def generateInquisitionDbConnection(self, dbUser, dbPass, dbName, dbHost='127.0.0.1', dbPort=3306):
"""
Generate main Inquisition database connection handler
:param dbUser: username of db account
:param dbPass: password of db account
:param dbName: name of database to connect to
:param dbHost: (Opt.) database host to connect to (default: 127.0.0.1)
:param dbPort: (Opt.) port to use when connecting to database host (default: 3306)
:return: PyMySQL connection obj
"""
return pymysql.connect(host=dbHost, port=dbPort, user=dbUser, password=dbPass, db=dbName,
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
def fetchParsers(self):
"""
Fetch parsing data from inquisition database
:return: dict
"""
parsers = {}
# fetch parsers from DB
sql = "SELECT " \
" parser_id, " \
" parser_name, " \
" parser_log " \
"FROM " \
" Parsers " \
"WHERE " \
" status = 1"
# execute query
with self.inquisitionDbHandle.cursor() as dbCursor:
dbCursor.execute(sql)
# fetch results
dbResults = dbCursor.fetchall()
for row in dbResults:
# add each parser to parser store
parsers[row['parser_id']] = Parser(lgr=self.lgr, inquisitionDbHandle=self.inquisitionDbHandle,
logDbHandle=self.logDbHandle, logTTL=self.cfg['parsing']['logTTL'],
maxLogsToProcess=self.cfg.getint('parsing', 'maxLogsToParse'),
parserID=row['parser_id'], parserName=row['parser_name'],
logFile=row['parser_log'],
keepPersistentStats=self.cfg.getboolean('stats', 'keepPersistentStats'),
metricsMode=self.cfg.getboolean('logging', 'enableMetricsMode'))
return parsers
def startAnatomizer(self):
"""
Begin cycle of polling of each Parser
:return: void
"""
# check if this is a test run
testRun = self.cfg.getboolean('cli', 'test_run')
# cycle through parsers
for parserId in self.parserStore:
# fork process before beginning read
self.lgr.debug('forking off parser [ ' + str(parserId) + ' - ' + self.parserStore[parserId].parserName
+ ' ] to child process')
newParserPID = fork()
if newParserPID == 0:
# in child process, start parsing
numRuns = 0
while True:
sleepTime = int(self.cfg['parsing']['sleepTime'])
numRunsBetweenStats = int(self.cfg['parsing']['numSleepsBetweenPolls'])
# poll for new logs
self.parserStore[parserId].pollLogFile(testRun,
useHazyStateTracking=self.cfg.getboolean(
'state_tracking', 'enableHazyStateTracking'),
numLogsBetweenTrackingUpdate=self.cfg.getint(
'state_tracking',
'stateTrackingWaitNumLogs'))
# check if running a test run
if testRun:
self.lgr.debug('test run, exiting anatomizer loop')
break
# run complete, increase counter
numRuns += 1
if numRuns >= numRunsBetweenStats:
# time to print stats and reset run counter
self.lgr.info('|-- PARSER STATS - GENERAL --| :: ' + str(self.parserStore[parserId]) + ' :: '
+ self.parserStore[parserId].printStats())
numRuns = 0
self.lgr.debug('sleeping for [ ' + self.cfg['parsing']['sleepTime'] + ' ] seconds')
sleep(sleepTime)
self.lgr.info('all templates loaded and parsers started SUCCESSFULLY')