ad2de25a0efb732f936e67cc853871b0c72a1731
[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                 table_ctx = self.create_table(self.ctxcols, self.ctxtab, 'char(80)', 'unique')
75                 c.execute(table_ctx)
76                 table_ev = self.create_table(self.evcols, self.evtab, 'double default null', '')
77                 c.execute(table_ev)
78                 self.conn.commit()
79
80                 if options.verbose:
81                         print 'go for gold'
82
83                 self.pidev  = self.ex(args, self.evtab, self.evfifo)
84                 self.pidctx = self.ex(args, self.ctxtab, self.ctxfifo)
85
86                 if options.verbose:
87                         print "forked two mysql leechers: %d, %d" % (self.pidev, self.pidctx)
88
89                 self.evfile   = open(self.evfifo, 'w+t')
90                 self.ctxfile  = open(self.ctxfifo, 'w+t')
91
92                 if options.verbose:
93                         print 'fifo:  %s, %o' % (self.evfile.name, os.stat(self.evfile.name).st_mode)
94                         print 'fifo:  %s, %o' % (self.ctxfile.name, os.stat(self.ctxfile.name).st_mode)
95
96         def ev(self, curr_id, evitems):
97                 field = ['\N'] * len(self.evcols)
98                 for key, val in evitems.iteritems():
99                         index = self.evcols[key]
100                         field[index] = val
101                 print >> self.evfile, ('%d;' % curr_id) + ';'.join(field)
102
103         def ctx(self, curr_id, ctxitems):
104                 field = ['\N'] * len(self.ctxcols)
105                 for key, val in ctxitems.iteritems():
106                         index = self.ctxcols[key]
107                         field[index] = val
108                 print >> self.ctxfile, ('%d;' % curr_id) + ';'.join(field)
109
110         def commit(self):
111                 self.evfile.close()
112                 self.ctxfile.close()
113
114                 os.waitpid(self.pidev, 0)
115                 os.waitpid(self.pidctx, 0)
116
117                 os.unlink(self.evfile.name)
118                 os.unlink(self.ctxfile.name)
119
120
121 class EmitSqlite3(EmitBase):
122         def __init__(self, options, tables, ctxcols, evcols):
123                 import sqlite3
124
125                 if options.database == None:
126                         print "Have to specify database (file-)name for sqlite"
127                         sys.exit(1)
128
129                 if os.path.isfile(options.database):
130                         os.unlink(options.database)
131
132                 self.ctxtab = tables['ctx']
133                 self.evtab  = tables['ev']
134                 self.conn = sqlite3.connect(options.database)
135                 table_ctx = self.create_table(ctxcols, self.ctxtab, 'text', 'unique')
136                 self.conn.execute(table_ctx)
137                 table_ev = self.create_table(evcols, self.evtab, 'double', '')
138                 self.conn.execute(table_ev)
139
140                 n = max(len(ctxcols), len(evcols)) + 1
141                 q = ['?']
142                 self.quests = []
143                 for i in xrange(0, n):
144                         self.quests.append(','.join(q))
145                         q.append('?')
146
147         def ev(self, curr_id, evitems):
148                 keys = ""
149                 first = True
150                 for key in evitems.keys():
151                         if first:
152                                 first = False
153                         else:
154                                 keys += ", "
155                         keys += "'%s'" % (key)
156
157                 stmt = "insert into '%s' (id, %s) values (%s)" % (self.evtab, keys, self.quests[len(evitems)])
158                 self.conn.execute(stmt, (curr_id,) + tuple(evitems.values()))
159
160         def ctx(self, curr_id, ctxitems):
161                 keys = ""
162                 first = True
163                 for key in ctxitems.keys():
164                         if first:
165                                 first = False
166                         else:
167                                 keys += ", "
168                         keys += "'%s'" % (key)
169
170                 stmt = "insert into '%s' (id, %s) values (%s)" % (self.ctxtab, keys, self.quests[len(ctxitems)])
171                 self.conn.execute(stmt, (curr_id,) + tuple(ctxitems.values()))
172
173         def commit(self):
174                 self.conn.commit()
175
176 class Conv:
177         engines = { 'sqlite3': EmitSqlite3, 'mysql': EmitMysqlInfile }
178         def find_heads(self):
179                 n_ev    = 0
180                 ctxind  = 0
181                 evind   = 0
182                 ctxcols = dict()
183                 evcols  = dict()
184
185                 self.valid_keys = set()
186
187                 inp = self.input()
188
189                 for line in inp:
190                         if line[0] == 'P':
191                                 ind = line.index(';', 2)
192                                 key = line[2:ind]
193                                 if not ctxcols.has_key(key):
194                                         ctxcols[key] = ctxind
195                                         ctxind += 1
196
197                         elif line[0] == 'E':
198                                 ind = line.index(';', 2)
199                                 key = line[2:ind]
200                                 if self.filter.match(key):
201                                         self.n_events += 1
202                                         if not evcols.has_key(key):
203                                                 self.valid_keys.add(key)
204                                                 evcols[key] = evind
205                                                 evind += 1
206
207                 return (ctxcols, evcols)
208
209         def input(self):
210                 return fileinput.FileInput(files=self.files, openhook=fileinput.hook_compressed)
211
212         def fill_tables(self):
213                 lineno     = 0
214                 ids        = 0
215                 curr_id    = 0
216                 last_push_curr_id = 0
217                 keystack   = []
218                 idstack    = []
219                 curr_event = 0
220                 last_prec  = -1
221                 evcols     = dict()
222                 ctxcols    = dict()
223
224                 for line in self.input():
225                         lineno += 1
226                         items = line.strip().split(';')
227                         op    = items[0]
228
229                         if op == 'P':
230                                 # flush the current events
231                                 if len(evcols):
232                                         self.emit.ev(last_push_curr_id, evcols)
233                                         evcols.clear()
234
235                                 # push the key
236                                 key   = items[1]
237                                 val   = items[2]
238                                 keystack.append(key)
239                                 curr_id = ids
240                                 last_push_curr_id = curr_id
241                                 ids += 1
242                                 idstack.append(curr_id)
243                                 ctxcols[key] = val
244
245                                 self.emit.ctx(curr_id, ctxcols)
246
247                         elif op == 'O':
248                                 popkey = items[1]
249                                 key = keystack.pop()
250
251                                 if popkey != key:
252                                         print "unmatched pop in line %d, push key %s, pop key: %s" % (lineno, key, popkey)
253
254                                 idstack.pop()
255                                 if len(idstack) > 0:
256                                         if len(evcols) > 0:
257                                                 self.emit.ev(curr_id, evcols)
258                                                 evcols.clear()
259                                         del ctxcols[key]
260                                         curr_id = idstack[-1]
261                                 else:
262                                         curr_id = -1
263
264                         elif op == 'E':
265                                 key = items[1]
266                                 if key in self.valid_keys:
267                                         curr_event += 1
268                                         evcols[key] = items[2]
269
270                                         if self.verbose:
271                                                 prec = curr_event * 10 / self.n_events
272                                                 if prec > last_prec:
273                                                         last_prec = prec
274                                                         print '%10d / %10d' % (curr_event, self.n_events)
275
276         def __init__(self):
277                 parser = optparse.OptionParser('usage: %prog [options]  <event file...>')
278                 parser.add_option("-c", "--clean",    dest="clean",    help="delete tables in advance", action="store_true", default=False)
279                 parser.add_option("-v", "--verbose",  dest="verbose",  help="verbose messages",         action="store_true", default=False)
280                 parser.add_option("-f", "--filter",   dest="filter",   help="regexp to filter event keys", metavar="REGEXP")
281                 parser.add_option("-u", "--user",     dest="user",     help="user",               metavar="USER")
282                 parser.add_option("-H", "--host",     dest="host",     help="host",               metavar="HOST")
283                 parser.add_option("-p", "--password", dest="password", help="password",           metavar="PASSWORD")
284                 parser.add_option("-d", "--db",       dest="database", help="database",           metavar="DB")
285                 parser.add_option("-e", "--engine",   dest="engine",   help="engine",             metavar="ENG", default='sqlite3')
286                 parser.add_option("-P", "--prefix",   dest="prefix",   help="table prefix",       metavar="PREFIX", default='')
287                 (options, args) = parser.parse_args()
288
289                 self.n_events = 0
290                 self.stmts    = dict()
291                 self.verbose  = options.verbose
292
293                 tables = dict()
294                 tables['ctx'] = options.prefix + 'ctx'
295                 tables['ev']  = options.prefix + 'ev'
296
297                 if len(args) < 1:
298                         parser.print_help()
299                         sys.exit(1)
300
301                 self.files  = []
302                 files       = args
303
304                 for file in files:
305                         if not os.path.isfile(file):
306                                 print "cannot find input file %s" % (file, )
307                         else:
308                                 self.files.append(file)
309
310                 if len(self.files) < 1:
311                         print "no input file to process"
312                         sys.exit(3)
313
314                 if options.filter:
315                         self.filter = re.compile(options.filter)
316                 else:
317                         self.filter = DummyFilter()
318
319                 if options.engine in self.engines:
320                         engine = self.engines[options.engine]
321                 else:
322                         print 'engine %s not found' % options.engine
323                         print 'we offer: %s' % self.engines.keys()
324                         sys.exit(0)
325
326                 if options.verbose:
327                         print "determining schema..."
328
329                 (ctxcols, evcols) = self.find_heads()
330                 if options.verbose:
331                         print "context schema:"
332                         print ctxcols
333                         print "event schema:"
334                         print evcols
335                         print "tables:"
336                         print tables
337
338                 self.emit = engine(options, tables, ctxcols, evcols)
339
340                 if options.verbose:
341                         print "filling tables..."
342                 self.fill_tables()
343                 if options.verbose:
344                         print "comitting..."
345                 self.emit.commit()
346
347 if __name__ == "__main__":
348         Conv()