only import datatbases that are actually used
[libfirm] / scripts / statev_sql.py
1 #! /usr/bin/env python
2
3 import sys
4 import os
5 import re
6 import time
7 import stat
8 import fileinput
9 import tempfile
10 import optparse
11
12 class DummyFilter:
13         def match(self, dummy):
14                 return True
15
16 class EmitBase:
17         def create_table(self, cols, name, type, unique):
18                 create = 'create table if not exists %s (id int %s' % (name, unique)
19
20                 sorted = [None] * len(cols)
21                 for x in cols.iterkeys():
22                         sorted[cols[x]] = x
23                 for x in sorted:
24                         create += (', %s %s' % (x, type))
25                 create += ');'
26                 return create
27
28 class EmitMysqlInfile(EmitBase):
29         tmpfile_mode = stat.S_IREAD | stat.S_IROTH | stat.S_IWUSR
30
31         def ex(self, args, tab, fname):
32                 res = os.fork()
33                 if res == 0:
34                         stmt = """load data infile '%s' into table %s fields terminated by ';'""" % (fname, tab)
35                         conn = MySQLdb.connect(**args)
36                         c = conn.cursor()
37                         c.execute(stmt)
38                         conn.commit()
39                         sys.exit(0)
40                 return res
41
42         def __init__(self, options, tables, ctxcols, evcols):
43                 import MySQLdb
44
45                 args = dict()
46                 if options.password:
47                         args['passwd'] = options.password
48                 if not options.host:
49                         options.host = 'localhost'
50                 args['user'] = options.user
51                 args['host'] = options.host
52                 args['db']   = options.database
53
54                 self.conn     = MySQLdb.connect(**args)
55                 self.ctxcols  = ctxcols
56                 self.evcols   = evcols
57                 self.options  = options
58                 self.ctxtab   = tables['ctx']
59                 self.evtab    = tables['ev']
60
61                 params = (tempfile.gettempdir(), os.sep, os.getpid())
62                 self.evfifo  = '%s%sstatev_ev_%d' % params
63                 self.ctxfifo = '%s%sstatev_ctx_%d' % params
64
65                 os.mkfifo(self.evfifo)
66                 os.mkfifo(self.ctxfifo)
67
68                 os.chmod(self.evfifo,  self.tmpfile_mode)
69                 os.chmod(self.ctxfifo, self.tmpfile_mode)
70
71                 c = self.conn.cursor()
72                 c.execute('drop table if exists ' + self.evtab)
73                 c.execute('drop table if exists ' + self.ctxtab)
74                 c.execute(self.create_table(self.ctxcols, self.ctxtab, 'char(80)', 'unique'))
75                 c.execute(self.create_table(self.evcols, self.evtab, 'double default null', ''))
76                 self.conn.commit()
77
78                 if options.verbose:
79                         print 'go for gold'
80
81                 self.pidev  = self.ex(args, self.evtab, self.evfifo)
82                 self.pidctx = self.ex(args, self.ctxtab, self.ctxfifo)
83
84                 if options.verbose:
85                         print "forked two mysql leechers: %d, %d" % (self.pidev, self.pidctx)
86
87                 self.evfile   = open(self.evfifo, 'w+t')
88                 self.ctxfile  = open(self.ctxfifo, 'w+t')
89
90                 if options.verbose:
91                         print 'fifo:  %s, %o' % (self.evfile.name, os.stat(self.evfile.name).st_mode)
92                         print 'fifo:  %s, %o' % (self.ctxfile.name, os.stat(self.ctxfile.name).st_mode)
93
94         def ev(self, curr_id, evitems):
95                 field = ['\N'] * len(self.evcols)
96                 for key, val in evitems.iteritems():
97                         index = self.evcols[key]
98                         field[index] = val
99                 print >> self.evfile, ('%d;' % curr_id) + ';'.join(field)
100
101         def ctx(self, curr_id, ctxitems):
102                 field = ['\N'] * len(self.ctxcols)
103                 for key, val in ctxitems.iteritems():
104                         index = self.ctxcols[key]
105                         field[index] = val
106                 print >> self.ctxfile, ('%d;' % curr_id) + ';'.join(field)
107
108         def commit(self):
109                 self.evfile.close()
110                 self.ctxfile.close()
111
112                 os.waitpid(self.pidev, 0)
113                 os.waitpid(self.pidctx, 0)
114
115                 os.unlink(self.evfile.name)
116                 os.unlink(self.ctxfile.name)
117
118
119 class EmitSqlite3(EmitBase):
120         def __init__(self, options, tables, ctxcols, evcols):
121                 import sqlite3
122
123                 if os.path.isfile(options.database):
124                         os.unlink(options.database)
125
126                 self.ctxtab = tables['ctx']
127                 self.evtab  = tables['ev']
128                 self.conn = sqlite3.connect(options.database)
129                 self.conn.execute(self.create_table(ctxcols, self.ctxtab, 'text', 'unique'))
130                 self.conn.execute(self.create_table(evcols, self.evtab, 'double', ''))
131
132                 n = max(len(ctxcols), len(evcols)) + 1
133                 q = ['?']
134                 self.quests = []
135                 for i in xrange(0, n):
136                         self.quests.append(','.join(q))
137                         q.append('?')
138
139         def ev(self, curr_id, evitems):
140                 keys = ','.join(evitems.keys())
141                 stmt = 'insert into %s (id, %s) values (%s)' % (self.evtab, keys, self.quests[len(evitems)])
142                 self.conn.execute(stmt, (curr_id,) + tuple(evitems.values()))
143
144         def ctx(self, curr_id, ctxitems):
145                 keys = ','.join(ctxitems.keys())
146                 stmt = 'insert into %s (id, %s) values (%s)' % (self.ctxtab, keys, self.quests[len(ctxitems)])
147                 self.conn.execute(stmt, (curr_id,) + tuple(ctxitems.values()))
148
149         def commit(self):
150                 self.conn.commit()
151
152 class Conv:
153         engines = { 'sqlite3': EmitSqlite3, 'mysql': EmitMysqlInfile }
154         def find_heads(self):
155                 n_ev    = 0
156                 ctxind   = 0
157                 evind    = 0
158                 ctxcols  = dict()
159                 evcols   = dict()
160
161                 self.valid_keys = set()
162
163                 for line in self.input():
164                         heads = None
165                         if line[0] == 'P':
166                                 ind = line.index(';', 2)
167                                 key = line[2:ind]
168                                 if not key in ctxcols:
169                                         ctxcols[key] = ctxind
170                                         ctxind += 1
171
172                         elif line[0] == 'E':
173                                 ind = line.index(';', 2)
174                                 key = line[2:ind]
175                                 if self.filter.match(key):
176                                         self.n_events += 1
177                                         if not key in evcols:
178                                                 self.valid_keys.add(key)
179                                                 evcols[key] = evind
180                                                 evind += 1
181
182                 return (ctxcols, evcols)
183
184         def input(self):
185                 return fileinput.FileInput(files=self.files, openhook=fileinput.hook_compressed)
186
187         def fill_tables(self):
188                 lineno     = 0
189                 ids        = 0
190                 curr_id    = 0
191                 keystack   = []
192                 idstack    = []
193                 curr_event = 0
194                 last_prec  = -1
195                 evcols     = dict()
196                 ctxcols    = dict()
197
198                 for line in self.input():
199                         lineno += 1
200                         items = line.strip().split(';')
201                         op    = items[0]
202
203                         if op == 'P':
204                                 # flush the current events
205                                 if len(evcols):
206                                         self.emit.ev(curr_id, evcols)
207                                         evcols.clear()
208
209                                 # push the key
210                                 key   = items[1]
211                                 val   = items[2]
212                                 keystack.append(key)
213                                 curr_id = ids
214                                 ids += 1
215                                 idstack.append(curr_id)
216                                 ctxcols[key] = val
217
218                                 self.emit.ctx(curr_id, ctxcols)
219
220                         elif op == 'O':
221                                 popkey = items[1]
222                                 key = keystack.pop()
223
224                                 if popkey != key:
225                                         print "unmatched pop in line %d, push key %s, pop key: %s" % (lineno, key, popkey)
226
227                                 idstack.pop()
228                                 if len(idstack) > 0:
229                                         if len(evcols) > 0:
230                                                 self.emit.ev(curr_id, evcols)
231                                                 evcols.clear()
232                                         del ctxcols[key]
233                                         curr_id = idstack[-1]
234                                 else:
235                                         curr_id = -1
236
237                         elif op == 'E':
238                                 key = items[1]
239                                 if key in self.valid_keys:
240                                         curr_event += 1
241                                         evcols[key] = items[2]
242
243                                         if self.verbose:
244                                                 prec = curr_event * 10 / self.n_events
245                                                 if prec > last_prec:
246                                                         last_prec = prec
247                                                         print '%10d / %10d' % (curr_event, self.n_events)
248
249         def __init__(self):
250                 parser = optparse.OptionParser('usage: %prog [options]  <event file...>')
251                 parser.add_option("-c", "--clean",    dest="clean",    help="delete tables in advance", action="store_true", default=False)
252                 parser.add_option("-v", "--verbose",  dest="verbose",  help="verbose messages",         action="store_true", default=False)
253                 parser.add_option("-f", "--filter",   dest="filter",   help="regexp to filter event keys", metavar="REGEXP")
254                 parser.add_option("-u", "--user",     dest="user",     help="user",               metavar="USER")
255                 parser.add_option("-H", "--host",     dest="host",     help="host",               metavar="HOST")
256                 parser.add_option("-p", "--password", dest="password", help="password",           metavar="PASSWORD")
257                 parser.add_option("-d", "--db",       dest="database", help="database",           metavar="DB")
258                 parser.add_option("-e", "--engine",   dest="engine",   help="engine",             metavar="ENG", default='sqlite3')
259                 parser.add_option("-P", "--prefix",   dest="prefix",   help="table prefix",       metavar="PREFIX", default='')
260                 (options, args) = parser.parse_args()
261
262                 self.n_events = 0
263                 self.stmts    = dict()
264                 self.verbose  = options.verbose
265
266                 tables = dict()
267                 tables['ctx'] = options.prefix + 'ctx'
268                 tables['ev']  = options.prefix + 'ev'
269
270                 if len(args) < 1:
271                         parser.print_help()
272                         sys.exit(1)
273
274                 self.files  = []
275                 files       = args
276
277                 for file in files:
278                         if not os.path.isfile(file):
279                                 print "cannot find input file %s" % (file, )
280                         else:
281                                 self.files.append(file)
282
283                 if len(self.files) < 1:
284                         print "no input file to process"
285                         sys.exit(3)
286
287                 if options.filter:
288                         self.filter = re.compile(options.filter)
289                 else:
290                         self.filter = DummyFilter()
291
292                 if options.engine in self.engines:
293                         engine = self.engines[options.engine]
294                 else:
295                         print 'engine %s not found' % options.engine
296                         print 'we offer: %s' % self.engines.keys()
297                         sys.exit(0)
298
299                 if options.verbose:
300                         print "determining schema..."
301
302                 (ctxcols, evcols) = self.find_heads()
303                 if options.verbose:
304                         print "context schema:"
305                         print ctxcols
306                         print "event schema:"
307                         print evcols
308                         print "tables:"
309                         print tables
310
311                 self.emit = engine(options, tables, ctxcols, evcols)
312
313                 if options.verbose:
314                         print "filling tables..."
315                 self.fill_tables()
316                 if options.verbose:
317                         print "comitting..."
318                 self.emit.commit()
319
320 if __name__ == "__main__":
321         Conv()