forked from stanford-futuredata/acidrain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_analyzer.py
executable file
·1578 lines (1488 loc) · 62.6 KB
/
log_analyzer.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from enum import Enum
import argparse
import datetime
import re
import sqlparse
import sys
import time
# THINGS TO DO:
# Add all columns to insert WS
# Add all columns to delete WS
# Read the write set of the thing
# see if the column of interest is in it
# if so, add the whole trace to the list of anomalies
# Can be extended with count, sum, etc.
class ReadType(Enum):
star = 1
cols = 2
class EdgeType(Enum):
RW = 1
WW = 2
class ValueType(Enum):
unknown = 1
string = 2
integer = 3
floating = 4
class KeyType(Enum):
pri = 1
uni = 2
mul = 3
class DbColType(Enum):
intlike = 1
floatlike = 2
stringlike = 3
datetimelike = 5
class QueryType(Enum):
notQuery = 1
other = 2
select = 3
update = 4
insert = 5
delete = 6
startTxn = 7
endTxn = 8
startTxnCond = 9 # set autocommit=0 starts a transaction if none is started
endTxnCond = 10 # set autocommit=1 commits a transaction if there is one
class OpNode:
def __init__(self, nodeId, logObj, txnNode, apiNode, forUpdates):
self.edgeMap = {}
self.nodeId = nodeId
self.edges = []
self.txn = txnNode
self.api = apiNode
# Should only matter if op1 and op2 of dfs are in select for update, otherwise it will
# be scope based anomaly. If they are, cannot go through any ops that have the same
# select for updates in place, or read or write any of the variables relevant to the select
# for update
self.forUpdates = forUpdates
self.logObj = logObj
class TxnNode:
def __init__(self, nodeId, apiNode):
self.edgeMap = {}
self.nodeId = nodeId
self.edges = []
self.ops = []
self.api = apiNode
class ApiNode:
def __init__(self, nodeId):
self.edgeMap = {}
self.nodeId = nodeId
self.edges = []
self.ops = []
self.txns = []
# The operations to which this node has an edge, used in our modified
# multilevel DFS. Mapping from nodeId to Edge Note that the op
# could be in this API node itself.
self.reachableOps = {}
class Edge:
def __init__(self, op1, op2, edgeType):
self.op1 = op1
self.op2 = op2
self.txn1 = op1.txn
self.txn2 = op2.txn
self.api1 = op1.api
self.api2 = op2.api
self.edgeType = edgeType
class AbstractHistory:
def __init__(self):
self.nodeMapping = {}
self.logObjMapping = {}
self.ops = []
self.txns = []
self.apis = []
self.totalEdges = 0
self.nextId = 0
def addOpNode(self, logObj, txnNode, apiNode, forUpdates):
newOp = OpNode(self.nextId, logObj, txnNode, apiNode, forUpdates)
self.ops.append(newOp)
txnNode.ops.append(newOp)
apiNode.ops.append(newOp)
self.nextId += 1
self.nodeMapping[newOp.nodeId] = newOp
self.logObjMapping[logObj.uniqueId] = newOp
return newOp
def addTxnNode(self, apiNode):
newTxn = TxnNode(self.nextId, apiNode)
self.txns.append(newTxn)
apiNode.txns.append(newTxn)
self.nextId += 1
self.nodeMapping[newTxn.nodeId] = newTxn
return newTxn
def addApiNode(self):
newApi = ApiNode(self.nextId)
self.apis.append(newApi)
self.nextId += 1
self.nodeMapping[newApi.nodeId] = newApi
return newApi
def addEdge(self, op1, op2, edgeType):
self.totalEdges += 1
edge1 = Edge(op1, op2, edgeType)
edge2 = Edge(op2, op1, edgeType)
txn1 = op1.txn
txn2 = op2.txn
api1 = op1.api
api2 = op2.api
op1.edges.append(edge1)
op2.edges.append(edge2)
op1.edgeMap[op2.nodeId] = edge1
op2.edgeMap[op1.nodeId] = edge2
txn1.edges.append(edge1)
txn2.edges.append(edge2)
api1.edges.append(edge1)
api2.edges.append(edge2)
lst1 = api1.reachableOps.get(op2.nodeId, [])
lst1.append(edge1)
api1.reachableOps[op2.nodeId] = lst1
lst2 = api2.reachableOps.get(op1.nodeId, [])
lst2.append(edge2)
api2.reachableOps[op1.nodeId] = lst2
def addSelfLoop(self, op):
self.totalEdges += 1
edge = Edge(op, op, EdgeType.WW)
op.edges.append(edge)
op.edgeMap[op.nodeId] = edge
op.txn.edges.append(edge)
op.api.edges.append(edge)
lst = op.api.reachableOps.get(op.nodeId, [])
lst.append(edge)
op.api.reachableOps[op.nodeId] = lst
def getNode(self, nodeId):
return self.nodeMapping[nodeId]
# Simplified version of depth first search to find simple anomalies.
# Focus on interesting to trigger AKA two api calls. Therefore,
# Each path of anomalies will consist of at most two ops, so return a list
# of lists where each inner list is either one or two ops used in the anomaly.
# The outer list will be empty if no anomaly is possible.
def find_potential_anomalies(self, op1, op2):
assert(op1.api == op2.api)
anomalyCausations = list()
toCheck = []
visited = {}
edgesUsed = []
reachedBy = {}
for edge in op1.edges:
if edge.api2.nodeId not in visited:
# Tuple of next api node to check, the edge we came from, and whether we
# should follow the edge by api (1) or by op (0)
toCheck.append((edge.api2, edge, 0))
visited[edge.api2.nodeId] = True
visited = {}
while len(toCheck) > 0:
(curApi, reachedByEdge, followOp) = toCheck.pop()
if curApi.nodeId in visited:
continue
reachedBy[curApi.nodeId] = (reachedByEdge, followOp)
visited[curApi.nodeId] = True
if op2.nodeId in curApi.reachableOps:
reachedBy[op2.nodeId] = (curApi.reachableOps[op2.nodeId][0], 1)
break
else:
for edge in curApi.edges:
toCheck.append((edge.api2, edge, 1))
if op2.nodeId in reachedBy:
(edge, followOp) = reachedBy[op2.nodeId]
path = [edge]
while edge.op1.nodeId != op1.nodeId:
nodeId = edge.api1.nodeId
if followOp == 0:
nodeId = edge.op1.nodeId
(edge, followOp) = reachedBy[nodeId]
path.append(edge)
path = list(reversed(path))
return path
else:
return None
class TableRead:
def __init__(self):
self.reads = {}
self.colsRead = []
def _strHelper(self):
strList = []
if ReadType.star in self.reads:
strList.append('*')
strList += self.colsRead
return str(strList)
def __str__(self):
return self._strHelper()
def __repr__(self):
return self._strHelper()
class DbSchema:
def __init__(self):
self.tables = {}
self.colTypes = {}
self.colDefaults = {}
self.colKeys = {}
def add(self, tableName, colName, colType, colDefault, colKey):
colList = self.tables.get(tableName, [])
colList.append(colName)
self.tables[tableName] = colList
key = (tableName, colName)
if colKey == 'PRI':
self.colKeys[key] = KeyType.pri
elif colKey == 'UNI':
self.colKeys[key] = KeyType.pri
elif colKey == 'MUL':
self.colKeys[key] = KeyType.pri
if 'int' in colType:
self.colTypes[key] = DbColType.intlike
elif 'decimal' in colType or 'double' in colType:
self.colTypes[key] = DbColType.floatlike
elif 'datetime' in colType:
self.colTypes[key] = DbColType.datetimelike
else:
self.colTypes[key] = DbColType.stringlike
self.colDefaults[key] = colDefault
class LogObject:
def __init__(self, timestamp, threadId, command, commArg, dbSchema, uid):
# Some identifier unique to the log for this program (e.g. it's line number)
self.uniqueId = uid
self.dbSchema = dbSchema
self.timestamp = timestamp
self.threadId = threadId
self.command = command
# Store the original comm arg to not be cleaned as well
self.origCommArg = commArg
self.commArg = self._cleanCommArg(commArg)
self.parsed = self._parseQueryCommArg()
self.queryType = self._calcQueryType()
self.writeSet = None
self.readSet = None
self.aliases = None
# The table in a select statement that unprefixed column names refers to
self.primaryTable = None
self.lowerCasedPT = False
self.tables = None
self.isNoop = None
self.whereFilter = None
def isWrite(self):
return ((self.queryType == QueryType.insert) or
(self.queryType == QueryType.update) or
(self.queryType == QueryType.delete))
def isRead(self):
return self.queryType == QueryType.select
# Remove some symbols that may make our string matching not work
def _cleanCommArg(self, commArg):
if (self.command == 'Query'):
commArg = commArg.replace('`', '')
return commArg
# Parse the query command arg
def _parseQueryCommArg(self):
if (self.command == 'Query'):
return sqlparse.parse(self.commArg)[0]
return None
def _calcQueryType(self):
if (self.parsed):
command = self.parsed.tokens[0].value.upper()
# Some other commands will fail the upper() conversion, but we don't care
# since the txn commands won't that that's why we need this
try:
commandTxnTest = str(self.parsed).upper()
except:
pass
if command == 'SELECT':
return QueryType.select
elif command == 'INSERT':
return QueryType.insert
elif command == 'UPDATE':
return QueryType.update
elif command == 'DELETE':
return QueryType.delete
elif (commandTxnTest == 'BEGIN' or
commandTxnTest == 'START TRANSACTION'):
return QueryType.startTxn
elif (commandTxnTest == 'COMMIT' or
commandTxnTest == 'ROLLBACK'):
return QueryType.endTxn
elif commandTxnTest == 'SET AUTOCOMMIT=0':
return QueryType.startTxnCond
elif commandTxnTest == 'SET AUTOCOMMIT=1':
return QueryType.endTxnCond
else:
return QueryType.other
return QueryType.notQuery
def isSelectForUpdate(self):
if self.queryType != QueryType.select:
return False
elif isinstance(self.parsed.tokens[-1], sqlparse.sql.Where):
tokens = self.parsed.tokens[-1].tokens
return (tokens[-1].value.upper() == 'UPDATE' and
tokens[-3].value.upper() == 'FOR')
else:
return (self.parsed.tokens[-1].value.upper() == 'UPDATE' and
self.parsed.tokens[-3].value.upper() == 'FOR')
def getPrimaryTable(self):
if (self.primaryTable != None):
if not self.lowerCasedPT:
self.lowerCasedPT = True
self.primaryTable = self.primaryTable.lower()
return self.primaryTable
else:
self.getTables()
self.lowerCasedPT = True
self.primaryTable = self.primaryTable.lower()
return self.primaryTable
def getAliases(self):
if (self.aliases != None):
return self.aliases
if self.queryType == QueryType.select:
self.aliases = self._getAliasesSelect()
else:
pt = self.getPrimaryTable()
self.aliases = {pt: pt}
return self.aliases
def _getAliasesSelect(self):
aliases = {}
addNextIdentifier = False
foundFrom = False
for t in self.parsed.tokens:
if (t.ttype == sqlparse.tokens.Keyword):
if (t.value.upper() == 'FROM'):
foundFrom = True
addNextIdentifier = True
if ('JOIN' in t.value.upper()):
addNextIdentifier = True
if ((t.__class__ == sqlparse.sql.Identifier or
t.__class__ == sqlparse.sql.IdentifierList) and addNextIdentifier):
if t.__class__ == sqlparse.sql.IdentifierList:
for subToken in t.tokens:
if subToken.__class__ == sqlparse.sql.Identifier:
# We don't handle subqueries right now, so just skip it
if ('SELECT' not in str(t)):
aliases[subToken.tokens[-1].value] = subToken.tokens[0].value
# We even let the fromTable be a select statement, nothing really goes
# wrong but no other queries will match it (saves some extra checks
# in getting the read set). Also this is not technically correct if
# there are multiple from tables but that is a rare case
if (foundFrom and not self.primaryTable):
self.primaryTable = subToken.tokens[0].value
else:
# We don't handle subqueries right now, so just skip it
if ('SELECT' not in str(t)):
aliases[t.tokens[-1].value] = t.tokens[0].value
# We even let the fromTable be a select statement, nothing really goes
# wrong but no other queries will match it (saves some extra checks
# in getting the read set
if (foundFrom):
self.primaryTable = t.tokens[0].value
foundFrom = False
addNextIdentifier = False
# This case has only so far occured with FOUND_ROWS()
if (self.primaryTable == None):
self.primaryTable = ''
return aliases
def getReadSet(self):
if (self.readSet != None):
return self.readSet
if self.queryType == QueryType.select:
aliases = self.getAliases()
fromIdx = 0
idx = 0
readSet = {}
for tbl in self.getTables():
readSet[tbl] = TableRead()
for t in self.parsed.tokens:
if (t.ttype == sqlparse.tokens.Keyword and
t.value.upper() == 'FROM'):
fromIdx = idx
break
idx += 1
if (fromIdx == 0):
# This case has only so far occured with FOUND_ROWS()
self.readSet = lowerCaseKeys(readSet)
return self.readSet
curIdx = fromIdx - 1
while (self.parsed.tokens[curIdx].ttype != sqlparse.tokens.Keyword.DML):
curIdx -= 1
acc = ''
for t in self.parsed.tokens[curIdx+1:fromIdx]:
acc += str(t)
readSplit = splitUncaptured(acc, '(', ')')
# sqlparse captures some sql keywords as part of the first read value
# so we do a nasty hack - just say all the things we should skip over
skippableWords = ['ALL', 'DISTINCT', 'DISTINCTION', 'HIGH_PRIORITY',
'STRAIGHT_JOIN', 'SQL_SMALL_STATEMENT', 'SQL_BIG_RESULT',
'SQL_BUFFER_RESULT', 'SQL_CACHE', 'SQL_NO_CACHE',
'SQL_CALC_FOUND_ROWS']
firstReadHelper = readSplit[0].split(' ')
idx = 0
for token in firstReadHelper:
if token not in skippableWords:
break
idx += 1
readSplit[0] = ' '.join(firstReadHelper[idx:])
for read in readSplit:
# Skip nested queries
if 'SELECT' in read:
continue
# This filters out functions and control flow.
# After testing, it only filters out 4 queries we care about so leaving it for now
if '(' in read:
continue
dotSplit = findFirstNonEmpty(read.split(' '), '', False).split('.')
if (len(dotSplit) == 2):
reads = readSet.get(aliases[dotSplit[0]], TableRead())
if '*' == dotSplit[1]:
reads.reads[ReadType.star] = '1'
else:
reads.reads[ReadType.cols] = '1'
reads.colsRead.append(dotSplit[1])
readSet[aliases[dotSplit[0]]] = reads
elif (len(dotSplit) == 1):
if '*' == dotSplit[0]:
for tbl in aliases.values():
reads = readSet.get(tbl, TableRead())
reads.reads[ReadType.star] = '1'
readSet[tbl] = reads
else:
reads = readSet.get(self.primaryTable, TableRead())
reads.reads[ReadType.cols] = '1'
reads.colsRead.append(dotSplit[0])
readSet[self.primaryTable] = reads
else:
raise Exception('Unexpected number of periods in column identifier')
self.readSet = readSet
else:
self.readSet = {}
self.readSet = lowerCaseKeys(self.readSet)
return self.readSet
# Returns the write set in the form of a mapping from columns to value
# A mapping to None indicates that the column was set in terms of some other column
def getWriteSet(self):
if (self.writeSet != None):
return self.writeSet
writeSet = {}
if self.queryType == QueryType.insert:
writeSet = self._getWriteSetInsert()
elif self.queryType == QueryType.update:
writeSet = self._getWriteSetUpdate()
elif self.queryType == QueryType.delete:
for col in self.dbSchema.tables[self.getPrimaryTable()]:
writeSet[col] = None
self.writeSet = writeSet
return self.writeSet
def _getWriteSetUpdate(self):
idxSet = 0
idxWhere = 0
for idx in xrange(0, len(self.parsed.tokens)):
t = self.parsed.tokens[idx]
if (t.ttype == sqlparse.tokens.Keyword and
t.value.upper() == 'SET'):
idxSet = idx
if (t.__class__ == sqlparse.sql.Where):
idxWhere = idx
# All updates in logs we have seen have both SET and WHERE in them
if (idxSet == 0 or idxWhere == 0):
raise Exception('This should never be reached in getWriteSetUpdate')
return self._getWriteSetSETSyntax(self.parsed.tokens[idxSet+1:idxWhere])
# This handles both the INSERT ... VALUES syntax and INSERT ... SET syntax
# Due to quirkiness of sqlparse, this does not handle "ON DUPLICATE KEY UPDATE"
# That can easily be added once we come across and app that uses that feature.
def _getWriteSetInsert(self):
writeSet = None
for idx in xrange(0, len(self.parsed.tokens)):
t = self.parsed.tokens[idx]
if (t.ttype == sqlparse.tokens.Keyword and
t.value.upper() == 'SET'):
writeSet = self._getWriteSetSETSyntax(self.parsed.tokens[idx + 2:])
if (t.ttype == sqlparse.tokens.Keyword and
(t.value.upper() == 'VALUES' or t.value.upper() == 'VALUE')):
writeSet = self._getWriteSetInsertValueSyntax(
self.parsed.tokens[idx + 2:], self.parsed.tokens[idx - 2])
if writeSet != None:
try:
cols = self.dbSchema.tables[self.getPrimaryTable()]
except:
# This happens when writing to a temporary table, which we don't handle for now
return {}
for col in cols:
if col not in writeSet:
writeSet[col] = None
return writeSet
raise Exception('This should never be reached in getWriteSetInsert')
def _getWriteSetSETSyntax(self, colsAndVals):
writeMapping = {}
acc = ''
# Stringify the input so that we can parse it ourselves since sqlparse
# does not appear to do this correctly
for token in colsAndVals:
acc += str(token)
for colAndVal in splitUnquoted(acc, ','):
eqIdx = colAndVal.index('=')
col = colAndVal[0:eqIdx].split('.')[-1].strip()
val = colAndVal[eqIdx+1:].strip()
self._insertIntoWriteMapWithCast(writeMapping, col, val)
return writeMapping
def _getWriteSetInsertValueSyntax(self, vals, cols):
writeMapping = {}
# Stringify the input so that we can parse it ourselves since sqlparse
# does not appear to do this correctly
accV = ""
for token in vals:
accV += token.value
# The case where the columns are specified, assume that sqlparse will
# treat this as a function and the columns are the arguments (validated on all apps)
colOrder = []
if cols.__class__ == sqlparse.sql.Function:
colNames = cols.tokens[2].value
# Strip surrounding parentheses
colNames = colNames[1:-1]
for s in colNames.split(','):
s = s.strip()
colOrder.append(s)
else:
return {}
# Uncomment below to test new logs for unhandled case
#raise Exception('Only handle case where cols are specified explicitly')
if (accV[-1] != ')'):
raise Exception('not ending in paren')
accV = accV[1:-1]
accV = splitUnquoted(accV, ')')[0]
splitVals = splitUnquoted(accV, ',')
for idx in xrange(0, len(splitVals)):
col = colOrder[idx]
val = splitVals[idx].strip()
self._insertIntoWriteMapWithCast(writeMapping, col, val)
return writeMapping
def _insertIntoWriteMapWithCast(self, writeMapping, col, val):
pt = self.getPrimaryTable()
inQuotes = False
if ((val[0] == "'" and val[-1] == "'")
or (val[0] == '"' and val[-1] == '"')):
inQuotes = True
val = val[1:-1]
if self.dbSchema.colTypes[(pt, col)] == DbColType.stringlike:
if not inQuotes and val != 'NULL' and val != '\N':
val = None
if self.dbSchema.colTypes[(pt, col)] == DbColType.intlike:
try:
val = int(val)
except:
val = None
if self.dbSchema.colTypes[(pt, col)] == DbColType.floatlike:
try:
val = float(val)
except:
val = None
writeMapping[col] = val
# Returns a mapping from columns to values.
# This allows us to do a very simple analyses where we treat each check in the WHERE
# as a big OR, which could/should be refined in the future
# Col -> [] indicates that it is not an equality mapping, so do not check value
# when checking overlap. This can be extended in the future if necessary
def getWhereFilter(self):
if self.whereFilter != None:
return self.whereFilter
if (self.queryType == QueryType.select or
self.queryType == QueryType.update or
self.queryType == QueryType.delete):
aliases = self.getAliases()
whereToken = None
filterMap = {}
for tbl in self.getTables():
filterMap[tbl] = {}
for t in self.parsed.tokens:
if (t.__class__ == sqlparse.sql.Where):
whereToken = t
# No Where clause
if (whereToken == None):
return filterMap
helperObj = {'waitingForConjunction': False,
'skipToNextConjunction': False}
# Hacky way to remove NOOP queries
if "1=0" in str(whereToken):
self.isNoop = True
return filterMap
self.isNoop = False
# Don't include the actual WHERE keyword itself
self._getWhereFilterHelper(whereToken.tokens[1:], filterMap, helperObj)
# TODO Add implied information about joined table filtering
self.whereFilter = lowerCaseKeys(filterMap)
return self.whereFilter
else:
print(self.origCommArg)
raise Exception('Trying to get where clause for invalid query type')
# Does the dirty work of parsing a WHERE clause
# Most assumptions are documented in the code in comments, exceptions,
# or setting skipToNextConjunction
def _getWhereFilterHelper(self, clauseTokens, filterMap, helperObj):
aliases = self.getAliases()
pt = self.getPrimaryTable()
foundIdentifier = False
curComparison = None
seenIn = False
seenIs = False
seenLike = False
seenValue = False
seenFunction = False
seenBetween = False
seenAnd = False
# Helps with the case where an identifier is mistaken for a keyword
expectingIdentifier = True
stringStart = None
numStart = None
for t in clauseTokens:
tUpperStr = str(t).upper()
if helperObj['skipToNextConjunction']:
if tUpperStr == 'AND' or tUpperStr == 'OR':
helperObj['waitingForConjunction'] = False
foundIdentifier = False
curComparison = None
seenIn = False
seenIs = False
seenLike = False
seenValue = False
seenFunction = False
seenBetween = False
seenAnd = False
expectingIdentifier = True
stringStart = None
numStart = None
helperObj['skipToNextConjunction'] = False
else:
continue
if t.__class__ == sqlparse.sql.Comparison:
if foundIdentifier or curComparison != None:
raise Exception('Unexpected comparison class placement')
self._getWhereFilterHelper(t.tokens, filterMap, helperObj)
elif t.__class__ == sqlparse.sql.Identifier:
if ((tUpperStr[0] == "'" and tUpperStr[-1] == "'") or
(tUpperStr[0] == '"' and tUpperStr[-1] == '"')):
seenValue = True
if foundIdentifier and curComparison != None:
self._insertWhereTblAndCol(filterMap, tbl, col, str(t),
curComparison, ValueType.string)
elif (foundIdentifier and seenLike) or (seenBetween and seenAnd):
self._insertWhereTblAndCol(filterMap, tbl, col, None,
None, ValueType.unknown)
else:
stringStart = str(t)
expectingIdentifier = False
elif ((stringStart != None and (seenLike or seenBetween or curComparison != None)) or
(numStart != None and curComparison != None)):
if len(t.tokens) == 1:
tbl = pt
col = str(t.tokens[0])
elif len(t.tokens) == 3:
tbl = aliases[str(t.tokens[0])]
col = str(t.tokens[2])
else:
raise Exception('Unexpected length of identifier tokens')
seenValue = True
if stringStart != None:
self._insertWhereTblAndCol(filterMap, tbl, col, stringStart,
curComparison, ValueType.string)
else:
self._insertWhereTblAndCol(filterMap, tbl, col, numStart,
curComparison, ValueType.integer) # may have to separate int and float here
helperObj['waitingForConjunction'] = seenLike or (seenBetween and seenAnd)
elif foundIdentifier and curComparison != None:
seenValue = True
self._insertWhereTblAndCol(filterMap, tbl, col, None,
curComparison, ValueType.unknown)
elif not helperObj['waitingForConjunction']:
foundIdentifier = True
expectingIdentifier = False
if len(t.tokens) == 1:
tbl = pt
col = str(t.tokens[0])
elif len(t.tokens) == 3:
tbl = aliases[str(t.tokens[0])]
col = str(t.tokens[2])
else:
raise Exception('Unexpected length of identifier tokens')
else:
raise Exception('Unexpected Identifier')
elif t.__class__ == sqlparse.sql.Parenthesis:
# Here we assume that anything we could compare to in parentheses is not
# something we would handle, so add the empty list to the map
if foundIdentifier and (seenIn or curComparison):
self._insertWhereTblAndCol(filterMap, tbl, col, None,
None, ValueType.unknown)
helperObj['waitingForConjunction'] = True
seenValue = True
elif foundIdentifier or seenIn or curComparison:
raise Exception('Only one of foundIdentifier and seenIn are set')
else:
# Chop off the parentheses themselves
self._getWhereFilterHelper(t.tokens[1:-1], filterMap, helperObj)
elif t.__class__ == sqlparse.sql.Function:
if foundIdentifier and curComparison != None:
self._insertWhereTblAndCol(filterMap, tbl, col, None,
None, ValueType.unknown)
seenValue = True
helperObj['waitingForConjunction'] = True
elif foundIdentifier or curComparison != None:
raise Exception('Only one of foundIdentifier and curComparison are set')
else:
seenFunction = True
expectingIdentifier = False
continue # Don't try to handle what happens inside of a function
elif t.__class__ == sqlparse.sql.Token:
if t.ttype == sqlparse.tokens.Whitespace:
continue
elif t.ttype == sqlparse.tokens.Keyword:
if helperObj['waitingForConjunction'] and (tUpperStr == 'AND' or tUpperStr == 'OR'):
helperObj['waitingForConjunction'] = False
foundIdentifier = False
curComparison = None
seenIn = False
seenIs = False
seenLike = False
seenValue = False
seenFunction = False
seenBetween = False
seenAnd = False
expectingIdentifier = True
stringStart = None
numStart = None
helperObj['skipToNextConjunction'] = False
elif seenBetween and tUpperStr == 'AND':
seenAnd = True
elif foundIdentifier:
if (tUpperStr not in ['NOT', 'LIKE', 'IS', 'IN', 'NULL', 'NOT NULL', 'BETWEEN'] and
not (helperObj['waitingForConjunction'] and tUpperStr in ['AND', 'OR'])):
raise Exception('Unexpected keyword following identifier')
else:
if curComparison != None and not seenValue:
raise Exception('Unexpected value for curComparison')
helperObj['waitingForConjunction'] = True
seenIn = seenIn or tUpperStr == 'IN'
seenIs = seenIs or tUpperStr == 'IS'
seenLike = seenLike or tUpperStr == 'LIKE'
seenBetween = seenBetween or tUpperStr == 'BETWEEN'
if tUpperStr in ['NULL', 'NOT NULL']:
if not seenIs:
raise Exception('NULL without first seeing IS')
self._insertWhereTblAndCol(filterMap, tbl, col, None,
None, ValueType.unknown)
seenValue = True
elif stringStart != None and not expectingIdentifier:
if tUpperStr not in ['NOT', 'LIKE', 'BETWEEN']:
raise Exception('Unexpected keyword following string')
else:
seenLike = seenLike or tUpperStr == 'LIKE'
seenBetween = seenBetween or tUpperStr == 'BETWEEN'
else:
if expectingIdentifier and str(t) != tUpperStr:
tbl = pt
col = str(t)
foundIdentifier = True
expectingIdentifier = False
if stringStart != None and curComparison != None:
self._insertWhereTblAndCol(filterMap, tbl, col, None,
None, ValueType.unknown)
else:
helperObj['skipToNextConjunction'] = True
#raise Exception('Unexpected keyword')
elif t.ttype == sqlparse.tokens.Operator.Comparison:
if not foundIdentifier:
if not (seenFunction or stringStart != None or numStart != None):
raise Exception('Comparison without identifier')
elif seenFunction:
# Hacky way to handle unknown functions of unknown cols:
# Just don't include them but dont' throw an error
helperObj['skipToNextConjunction'] = True
elif stringStart != None or numStart != None:
expectingIdentifier = True
curComparison = tUpperStr
if curComparison not in ['=', '<', '<=', '>', '>=', '!=', '<>']:
raise Exception('Unknown comparison')
helperObj['waitingForConjunction'] = True
elif t.ttype == sqlparse.tokens.Name.Builtin:
# Manual inspection indicates that this is safe to just skip over
if tUpperStr == 'BINARY':
continue
else:
raise Exception('Unknown token of Builtin ttype')
elif t.ttype == sqlparse.tokens.Literal.String.Single:
seenValue = True
if foundIdentifier and curComparison != None:
self._insertWhereTblAndCol(filterMap, tbl, col, str(t),
curComparison, ValueType.string)
elif (foundIdentifier and seenLike) or (seenBetween and seenAnd):
self._insertWhereTblAndCol(filterMap, tbl, col, str(t),
None, ValueType.string)
else:
stringStart = str(t)
expectingIdentifier = False
elif t.ttype == sqlparse.tokens.Literal.Number.Integer:
seenValue = True
if foundIdentifier and curComparison != None:
self._insertWhereTblAndCol(filterMap, tbl, col, str(t),
curComparison, ValueType.integer)
elif expectingIdentifier:
numStart = int(tUpperStr)
expectingIdentifier = False
else:
raise Exception('Unexpected integer literal placement')
elif t.ttype == sqlparse.tokens.Literal.Number.Float:
seenValue = True
if foundIdentifier and curComparison != None:
self._insertWhereTblAndCol(filterMap, tbl, col, str(t),
curComparison, ValueType.floating)
else:
raise Exception('Unexpected float literal placement')
elif t.ttype == sqlparse.tokens.Keyword.DML:
# Don't handle nested queries
helperObj['skipToNextConjunction'] = True
return
else:
raise Exception('Unexpected ttype')
else:
raise Exception('Unexpected class')
def _insertWhereTblAndCol(self, filterMap, tbl, col, val, curComparison, valType):
colMap = filterMap.get(tbl, {})
# All table names are lower case in schema description
tbl = tbl.lower()
if curComparison == '=' and val != None:
vals = colMap.get(col, [])
if valType == ValueType.string:
if (not ((val[0] == "'" and val[-1] == "'")
or (val[0] == '"' and val[-1] == '"'))):
raise Exception('String does not have expected format')
val = val[1:-1]
if self.dbSchema.colTypes[(tbl, col)] == DbColType.intlike:
val = int(val)
if self.dbSchema.colTypes[(tbl, col)] == DbColType.floatlike:
val = float(val)
elif valType == ValueType.integer:
val = int(val)
elif valType == ValueType.floating:
val = float(val)
else:
raise Exception('Should never be reached')
vals.append(val)
colMap[col] = vals
else:
colMap[col] = []
filterMap[tbl] = colMap
# Should also set primaryTable
def getTables(self):
if self.tables is not None:
return self.tables
tables = None
if self.queryType == QueryType.select:
aliases = self.getAliases()
tables = aliases.values()
elif self.queryType == QueryType.update:
tables = self._getTablesUpdate()
elif self.queryType == QueryType.insert:
tables = self._getTablesInsert()
elif self.queryType == QueryType.delete:
tables = self._getTablesDelete()
else:
tables = []
newTables = []
for t in tables:
newTables.append(t.lower())
self.tables = newTables
return self.tables
def _getTablesUpdate(self):
# tokens will have 'UPDATE', whitespace, table name
# The second tokens extracts just the name in case of aliasing
self.primaryTable = self.parsed.tokens[2].tokens[0].value
return [self.primaryTable]
def _getTablesInsert(self):
# tokens will have 'INSERT', whitespace, 'INTO', whitespace, table name
# or just 'INSERT', whitespace, table name
# The second tokens extracts just the name in case of aliasing
for t in self.parsed.tokens:
if (t.__class__ == sqlparse.sql.Identifier):
self.primaryTable = t.tokens[0].value
break
if (t.__class__ == sqlparse.sql.Function):
self.primaryTable = t.tokens[0].tokens[0].value
break
return [self.primaryTable]
def _getTablesDelete(self):
# tokens will have 'DELETE', whitespace, 'FROM', whitespace, table name
# The second tokens extracts just the name in case of aliasing
self.primaryTable = self.parsed.tokens[4].tokens[0].value
return [self.primaryTable]
def __str__(self):
return self._printHelper()
def __repr__(self):
return self._printHelper()
def _printHelper(self):
return '\n'.join([str(self.uniqueId), self.origCommArg])
# Reads the db schema info csv (format is table_name,col_name,col_key)
def readDbSchemaFile(fName):
dbSchema = DbSchema()
with open(fName, 'r') as f:
for line in f:
# Remove newline at end of string
line = line[:-1]
csplit = line.split(',')
dbSchema.add(csplit[0], csplit[1], csplit[2], csplit[3], csplit[4])
return dbSchema
# Reads the raw logs and ensures that every line is a single
# log line (no comments, combines lines if formatted strangely)
def readRawLogs(fName):
logs = []
with open(fName, 'r') as f:
currentLine = ''
for line in f:
# Skip comments
if (line[0] == '#'):
continue
# Remove newline at end of string
line = line[:-1]
continuation = False
# Check if the line is part of the previous log or a new log
for i in xrange(len(line)):
c = line[i]
if (c == ' ' or c == '\t'):
continue
try:
int(c)
logs.append(currentLine)
currentLine = line
except ValueError:
currentLine += ' ' + line[i:]
break