Debian Codegraph @

contrib/tracking_module_usage/gen_2/store_module_data

raw
1 #!/bin/sh
2 # -*- python -*-
3
4 ################################################################################
5 # This file is python 2/3 bilingual.
6 # The line """:" starts a comment in python and is a no-op in shell.
7 """:"
8 # Shell code to find and run a suitable python interpreter.
9 for cmd in python3 python python2; do
10 command -v > /dev/null $cmd && exec $cmd $0 "$@"
11 done
12
13 echo "Error: Could not find a valid python interpreter --> exiting!" >&2
14 exit 2
15 ":""" # this line ends the python comment and is a no-op in shell.
16 ################################################################################
17
18 from __future__ import print_function
19 import os, sys, re, time, argparse, json, operator
20 from LMODdb import LMODdb
21
22 def syshost(name):
23 hostA = name.split('.')
24 idx = 1
25 if (len(hostA) < 2):
26 idx = 0
27 return hostA[idx]
28
29 class CmdLineOptions(object):
30 """ Command line Options class """
31
32 def __init__(self):
33 """ Empty Ctor """
34 pass
35
36 def execute(self):
37 """ Specify command line arguments and parse the command line"""
38 parser = argparse.ArgumentParser()
39 parser.add_argument("-D", dest='debug', action="store_true", help="Debug Flag")
40 parser.add_argument("--delete", dest='delete', action="store_true", default=False, help="delete file after processing")
41 parser.add_argument("--store_all", dest='storeAll', action="store_true", default=False, help="Store all modules and not deduplicate")
42 parser.add_argument("--confFn", dest='confFn', action="store", default="lmodV2_db.conf", help="DB config file")
43 parser.add_argument("--ignoreFn", dest='ignoreFn', action="store", help="List of module patterns to ignore")
44 parser.add_argument('dataFnA', metavar='dataFnA', type=str, nargs='+', help='a list of Syslog/Json files to process')
45 args = parser.parse_args()
46 return args
47
48
49 class Ignore(object):
50 def __init__(self, ignoreFn):
51 if (not ignoreFn):
52 self.__ignoreA = []
53 return
54
55 ignoreA = []
56 with open(ignoreFn, 'r') as file:
57 # Read each line in the file
58 for line in file:
59 ignoreA.append(re.compile(line.strip()))
60 self.__ignoreA = ignoreA
61
62 def ignore(self, module):
63 result = False
64 for rex in self.__ignoreA:
65 match = rex.match(module)
66 if (match):
67 result = True
68 break
69
70 return result
71
72
73 class Reader(object):
74 def __init__(self, debug, ignore, ext, lmod):
75 self.debug = debug
76 self.ignore = ignore
77 self.ext = ext
78 self.lmod = lmod
79 self.modulePatt = re.compile(r'.*ModuleUsageTracking[^ ]* *')
80
81 def handleOneLine(self, line):
82 line = line.rstrip()
83 if (len(line) < 1):
84 return None
85
86 if (self.ext == '.json'):
87 dataT = json.loads(line)
88 else:
89 rest = self.modulePatt.sub('',line)
90 dataT = dict(re.findall(r'(\S+)=(".*?"|\S+)', rest))
91 host = dataT.get('host')
92 dataT['syshost'] = syshost(host)
93 dataT['date'] = dataT['time']
94 dataT.pop('time',None)
95 dataT.pop('host',None)
96
97 if (dataT.get('syshost') == None):
98 dataT = None
99 elif (self.ignore.ignore(dataT.get('module'))):
100 dataT = None
101
102 return dataT
103
104 class StoreAll(Reader):
105 def __init__(self, debug, ignore, ext, lmod):
106 super().__init__(debug, ignore, ext, lmod)
107 self.__blkSz = 1000
108 self.__icount = 0
109 self.__dataA = []
110
111 def storeOneLine(self, dataT):
112 self.__icount += 1
113 self.__dataA.append(dataT.copy())
114 if (self.__icount >= self.__blkSz):
115 self.lmod.data_to_db(self.debug, self.__dataA)
116 self.__dataA.clear()
117 self.__icount = 0
118
119 def save(self):
120 if (len(self.__dataA) > 0):
121 self.lmod.data_to_db(self.debug, self.__dataA)
122
123
124 class Dedup(Reader):
125 def __init__(self, debug, ignore, ext, lmod):
126 self.__usageT = {}
127 super().__init__(debug, ignore, ext, lmod)
128
129 def storeOneLine(self, dataT):
130 key = dataT['user'] + ' ' + dataT['syshost'] + ' ' + dataT['module'] + ' ' + dataT['path']
131 if (not key in self.__usageT):
132 self.__usageT[key] = { 'user' : dataT['user'],
133 'syshost' : dataT['syshost'],
134 'module' : dataT['module'],
135 'path' : dataT['path'],
136 'date' : dataT['date'],
137 }
138 def save(self):
139 dataA = []
140 for value in self.__usageT.values():
141 dataA.append(value.copy())
142 dataA.sort(key=operator.itemgetter('date'))
143
144 if (len(dataA) > 0):
145 self.lmod.data_to_db(self.debug, dataA)
146
147
148 def main():
149
150 args = CmdLineOptions().execute()
151 lmod = LMODdb(args.confFn)
152 ignore = Ignore(args.ignoreFn)
153
154 for dataFn in args.dataFnA:
155 baseNm, extension = os.path.splitext(dataFn)
156 if (args.storeAll):
157 reader = StoreAll(args.debug, ignore, extension, lmod)
158 else:
159 reader = Dedup(args.debug, ignore, extension, lmod)
160
161 if (not os.path.exists(dataFn)):
162 continue
163 with open(dataFn, "r") as file:
164 for line in file:
165 dataT = reader.handleOneLine(line)
166 if (not dataT):
167 continue
168 reader.storeOneLine(dataT)
169
170 reader.save()
171 if (args.delete):
172 os.remove(dataFn)
173
174
175
176 if ( __name__ == '__main__'): main()