13 def match(self, dummy):
17 def create_table(self, cols, name, type, unique):
18 create = 'create table if not exists %s (id int %s' % (name, unique)
20 sorted = [None] * len(cols)
21 for x in cols.iterkeys():
24 create += (', %s %s' % (x, type))
28 class EmitMysqlInfile(EmitBase):
29 tmpfile_mode = stat.S_IREAD | stat.S_IROTH | stat.S_IWUSR
31 def ex(self, args, tab, fname):
34 stmt = """load data infile '%s' into table %s fields terminated by ';'""" % (fname, tab)
35 conn = MySQLdb.connect(**args)
42 def __init__(self, options, tables, ctxcols, evcols):
47 args['passwd'] = options.password
49 options.host = 'localhost'
50 args['user'] = options.user
51 args['host'] = options.host
52 args['db'] = options.database
54 self.conn = MySQLdb.connect(**args)
55 self.ctxcols = ctxcols
57 self.options = options
58 self.ctxtab = tables['ctx']
59 self.evtab = tables['ev']
61 params = (tempfile.gettempdir(), os.sep, os.getpid())
62 self.evfifo = '%s%sstatev_ev_%d' % params
63 self.ctxfifo = '%s%sstatev_ctx_%d' % params
65 os.mkfifo(self.evfifo)
66 os.mkfifo(self.ctxfifo)
68 os.chmod(self.evfifo, self.tmpfile_mode)
69 os.chmod(self.ctxfifo, self.tmpfile_mode)
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', ''))
81 self.pidev = self.ex(args, self.evtab, self.evfifo)
82 self.pidctx = self.ex(args, self.ctxtab, self.ctxfifo)
85 print "forked two mysql leechers: %d, %d" % (self.pidev, self.pidctx)
87 self.evfile = open(self.evfifo, 'w+t')
88 self.ctxfile = open(self.ctxfifo, 'w+t')
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)
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]
99 print >> self.evfile, ('%d;' % curr_id) + ';'.join(field)
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]
106 print >> self.ctxfile, ('%d;' % curr_id) + ';'.join(field)
112 os.waitpid(self.pidev, 0)
113 os.waitpid(self.pidctx, 0)
115 os.unlink(self.evfile.name)
116 os.unlink(self.ctxfile.name)
119 class EmitSqlite3(EmitBase):
120 def __init__(self, options, tables, ctxcols, evcols):
123 if os.path.isfile(options.database):
124 os.unlink(options.database)
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', ''))
132 n = max(len(ctxcols), len(evcols)) + 1
135 for i in xrange(0, n):
136 self.quests.append(','.join(q))
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()))
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()))
153 engines = { 'sqlite3': EmitSqlite3, 'mysql': EmitMysqlInfile }
154 def find_heads(self):
161 self.valid_keys = set()
163 for line in self.input():
166 ind = line.index(';', 2)
168 if not key in ctxcols:
169 ctxcols[key] = ctxind
173 ind = line.index(';', 2)
175 if self.filter.match(key):
177 if not key in evcols:
178 self.valid_keys.add(key)
182 return (ctxcols, evcols)
185 return fileinput.FileInput(files=self.files, openhook=fileinput.hook_compressed)
187 def fill_tables(self):
198 for line in self.input():
200 items = line.strip().split(';')
204 # flush the current events
206 self.emit.ev(curr_id, evcols)
215 idstack.append(curr_id)
218 self.emit.ctx(curr_id, ctxcols)
225 print "unmatched pop in line %d, push key %s, pop key: %s" % (lineno, key, popkey)
230 self.emit.ev(curr_id, evcols)
233 curr_id = idstack[-1]
239 if key in self.valid_keys:
241 evcols[key] = items[2]
244 prec = curr_event * 10 / self.n_events
247 print '%10d / %10d' % (curr_event, self.n_events)
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()
264 self.verbose = options.verbose
267 tables['ctx'] = options.prefix + 'ctx'
268 tables['ev'] = options.prefix + 'ev'
278 if not os.path.isfile(file):
279 print "cannot find input file %s" % (file, )
281 self.files.append(file)
283 if len(self.files) < 1:
284 print "no input file to process"
288 self.filter = re.compile(options.filter)
290 self.filter = DummyFilter()
292 if options.engine in self.engines:
293 engine = self.engines[options.engine]
295 print 'engine %s not found' % options.engine
296 print 'we offer: %s' % self.engines.keys()
300 print "determining schema..."
302 (ctxcols, evcols) = self.find_heads()
304 print "context schema:"
306 print "event schema:"
311 self.emit = engine(options, tables, ctxcols, evcols)
314 print "filling tables..."
320 if __name__ == "__main__":