fix bug in statev script for empty contexts
[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 options.database == None:
124                         print "Have to specify database (file-)name for sqlite"
125                         sys.exit(1)
126
127                 if os.path.isfile(options.database):
128                         os.unlink(options.database)
129
130                 self.ctxtab = tables['ctx']
131                 self.evtab  = tables['ev']
132                 self.conn = sqlite3.connect(options.database)
133                 self.conn.execute(self.create_table(ctxcols, self.ctxtab, 'text', 'unique'))
134                 self.conn.execute(self.create_table(evcols, self.evtab, 'double', ''))
135
136                 n = max(len(ctxcols), len(evcols)) + 1
137                 q = ['?']
138                 self.quests = []
139                 for i in xrange(0, n):
140                         self.quests.append(','.join(q))
141                         q.append('?')
142
143         def ev(self, curr_id, evitems):
144                 keys = ','.join(evitems.keys())
145                 stmt = 'insert into %s (id, %s) values (%s)' % (self.evtab, keys, self.quests[len(evitems)])
146                 self.conn.execute(stmt, (curr_id,) + tuple(evitems.values()))
147
148         def ctx(self, curr_id, ctxitems):
149                 keys = ','.join(ctxitems.keys())
150                 stmt = 'insert into %s (id, %s) values (%s)' % (self.ctxtab, keys, self.quests[len(ctxitems)])
151                 self.conn.execute(stmt, (curr_id,) + tuple(ctxitems.values()))
152
153         def commit(self):
154                 self.conn.commit()
155
156 class Conv:
157         engines = { 'sqlite3': EmitSqlite3, 'mysql': EmitMysqlInfile }
158         def find_heads(self):
159                 n_ev    = 0
160                 ctxind  = 0
161                 evind   = 0
162                 ctxcols = dict()
163                 evcols  = dict()
164
165                 self.valid_keys = set()
166
167                 inp = self.input()
168
169                 for line in inp:
170                         if line[0] == 'P':
171                                 ind = line.index(';', 2)
172                                 key = line[2:ind]
173                                 if not ctxcols.has_key(key):
174                                         ctxcols[key] = ctxind
175                                         ctxind += 1
176
177                         elif line[0] == 'E':
178                                 ind = line.index(';', 2)
179                                 key = line[2:ind]
180                                 if self.filter.match(key):
181                                         self.n_events += 1
182                                         if not evcols.has_key(key):
183                                                 self.valid_keys.add(key)
184                                                 evcols[key] = evind
185                                                 evind += 1
186
187                 return (ctxcols, evcols)
188
189         def input(self):
190                 return fileinput.FileInput(files=self.files, openhook=fileinput.hook_compressed)
191
192         def fill_tables(self):
193                 lineno     = 0
194                 ids        = 0
195                 curr_id    = 0
196                 last_push_curr_id = 0
197                 keystack   = []
198                 idstack    = []
199                 curr_event = 0
200                 last_prec  = -1
201                 evcols     = dict()
202                 ctxcols    = dict()
203
204                 for line in self.input():
205                         lineno += 1
206                         items = line.strip().split(';')
207                         op    = items[0]
208
209                         if op == 'P':
210                                 # flush the current events
211                                 if len(evcols):
212                                         self.emit.ev(last_push_curr_id, evcols)
213                                         evcols.clear()
214
215                                 # push the key
216                                 key   = items[1]
217                                 val   = items[2]
218                                 keystack.append(key)
219                                 curr_id = ids
220                                 last_push_curr_id = curr_id
221                                 ids += 1
222                                 idstack.append(curr_id)
223                                 ctxcols[key] = val
224
225                                 self.emit.ctx(curr_id, ctxcols)
226
227                         elif op == 'O':
228                                 popkey = items[1]
229                                 key = keystack.pop()
230
231                                 if popkey != key:
232                                         print "unmatched pop in line %d, push key %s, pop key: %s" % (lineno, key, popkey)
233
234                                 idstack.pop()
235                                 if len(idstack) > 0:
236                                         if len(evcols) > 0:
237                                                 self.emit.ev(curr_id, evcols)
238                                                 evcols.clear()
239                                         del ctxcols[key]
240                                         curr_id = idstack[-1]
241                                 else:
242                                         curr_id = -1
243
244                         elif op == 'E':
245                                 key = items[1]
246                                 if key in self.valid_keys:
247                                         curr_event += 1
248                                         evcols[key] = items[2]
249
250                                         if self.verbose:
251                                                 prec = curr_event * 10 / self.n_events
252                                                 if prec > last_prec:
253                                                         last_prec = prec
254                                                         print '%10d / %10d' % (curr_event, self.n_events)
255
256         def __init__(self):
257                 parser = optparse.OptionParser('usage: %prog [options]  <event file...>')
258                 parser.add_option("-c", "--clean",    dest="clean",    help="delete tables in advance", action="store_true", default=False)
259                 parser.add_option("-v", "--verbose",  dest="verbose",  help="verbose messages",         action="store_true", default=False)
260                 parser.add_option("-f", "--filter",   dest="filter",   help="regexp to filter event keys", metavar="REGEXP")
261                 parser.add_option("-u", "--user",     dest="user",     help="user",               metavar="USER")
262                 parser.add_option("-H", "--host",     dest="host",     help="host",               metavar="HOST")
263                 parser.add_option("-p", "--password", dest="password", help="password",           metavar="PASSWORD")
264                 parser.add_option("-d", "--db",       dest="database", help="database",           metavar="DB")
265                 parser.add_option("-e", "--engine",   dest="engine",   help="engine",             metavar="ENG", default='sqlite3')
266                 parser.add_option("-P", "--prefix",   dest="prefix",   help="table prefix",       metavar="PREFIX", default='')
267                 (options, args) = parser.parse_args()
268
269                 self.n_events = 0
270                 self.stmts    = dict()
271                 self.verbose  = options.verbose
272
273                 tables = dict()
274                 tables['ctx'] = options.prefix + 'ctx'
275                 tables['ev']  = options.prefix + 'ev'
276
277                 if len(args) < 1:
278                         parser.print_help()
279                         sys.exit(1)
280
281                 self.files  = []
282                 files       = args
283
284                 for file in files:
285                         if not os.path.isfile(file):
286                                 print "cannot find input file %s" % (file, )
287                         else:
288                                 self.files.append(file)
289
290                 if len(self.files) < 1:
291                         print "no input file to process"
292                         sys.exit(3)
293
294                 if options.filter:
295                         self.filter = re.compile(options.filter)
296                 else:
297                         self.filter = DummyFilter()
298
299                 if options.engine in self.engines:
300                         engine = self.engines[options.engine]
301                 else:
302                         print 'engine %s not found' % options.engine
303                         print 'we offer: %s' % self.engines.keys()
304                         sys.exit(0)
305
306                 if options.verbose:
307                         print "determining schema..."
308
309                 (ctxcols, evcols) = self.find_heads()
310                 if options.verbose:
311                         print "context schema:"
312                         print ctxcols
313                         print "event schema:"
314                         print evcols
315                         print "tables:"
316                         print tables
317
318                 self.emit = engine(options, tables, ctxcols, evcols)
319
320                 if options.verbose:
321                         print "filling tables..."
322                 self.fill_tables()
323                 if options.verbose:
324                         print "comitting..."
325                 self.emit.commit()
326
327 if __name__ == "__main__":
328         Conv()