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