1# export-to-postgresql.py: export perf data to a postgresql database
2# Copyright (c) 2014, Intel Corporation.
3#
4# This program is free software; you can redistribute it and/or modify it
5# under the terms and conditions of the GNU General Public License,
6# version 2, as published by the Free Software Foundation.
7#
8# This program is distributed in the hope it will be useful, but WITHOUT
9# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11# more details.
12
13from __future__ import print_function
14
15import os
16import sys
17import struct
18import datetime
19
20# To use this script you will need to have installed package python-pyside which
21# provides LGPL-licensed Python bindings for Qt.  You will also need the package
22# libqt4-sql-psql for Qt postgresql support.
23#
24# The script assumes postgresql is running on the local machine and that the
25# user has postgresql permissions to create databases. Examples of installing
26# postgresql and adding such a user are:
27#
28# fedora:
29#
30#	$ sudo yum install postgresql postgresql-server python-pyside qt-postgresql
31#	$ sudo su - postgres -c initdb
32#	$ sudo service postgresql start
33#	$ sudo su - postgres
34#	$ createuser <your user id here>
35#	Shall the new role be a superuser? (y/n) y
36#
37# ubuntu:
38#
39#	$ sudo apt-get install postgresql python-pyside.qtsql libqt4-sql-psql
40#	$ sudo su - postgres
41#	$ createuser -s <your user id here>
42#
43# An example of using this script with Intel PT:
44#
45#	$ perf record -e intel_pt//u ls
46#	$ perf script -s ~/libexec/perf-core/scripts/python/export-to-postgresql.py pt_example branches calls
47#	2015-05-29 12:49:23.464364 Creating database...
48#	2015-05-29 12:49:26.281717 Writing to intermediate files...
49#	2015-05-29 12:49:27.190383 Copying to database...
50#	2015-05-29 12:49:28.140451 Removing intermediate files...
51#	2015-05-29 12:49:28.147451 Adding primary keys
52#	2015-05-29 12:49:28.655683 Adding foreign keys
53#	2015-05-29 12:49:29.365350 Done
54#
55# To browse the database, psql can be used e.g.
56#
57#	$ psql pt_example
58#	pt_example=# select * from samples_view where id < 100;
59#	pt_example=# \d+
60#	pt_example=# \d+ samples_view
61#	pt_example=# \q
62#
63# An example of using the database is provided by the script
64# exported-sql-viewer.py.  Refer to that script for details.
65#
66# Tables:
67#
68#	The tables largely correspond to perf tools' data structures.  They are largely self-explanatory.
69#
70#	samples
71#
72#		'samples' is the main table. It represents what instruction was executing at a point in time
73#		when something (a selected event) happened.  The memory address is the instruction pointer or 'ip'.
74#
75#	calls
76#
77#		'calls' represents function calls and is related to 'samples' by 'call_id' and 'return_id'.
78#		'calls' is only created when the 'calls' option to this script is specified.
79#
80#	call_paths
81#
82#		'call_paths' represents all the call stacks.  Each 'call' has an associated record in 'call_paths'.
83#		'calls_paths' is only created when the 'calls' option to this script is specified.
84#
85#	branch_types
86#
87#		'branch_types' provides descriptions for each type of branch.
88#
89#	comm_threads
90#
91#		'comm_threads' shows how 'comms' relates to 'threads'.
92#
93#	comms
94#
95#		'comms' contains a record for each 'comm' - the name given to the executable that is running.
96#
97#	dsos
98#
99#		'dsos' contains a record for each executable file or library.
100#
101#	machines
102#
103#		'machines' can be used to distinguish virtual machines if virtualization is supported.
104#
105#	selected_events
106#
107#		'selected_events' contains a record for each kind of event that has been sampled.
108#
109#	symbols
110#
111#		'symbols' contains a record for each symbol.  Only symbols that have samples are present.
112#
113#	threads
114#
115#		'threads' contains a record for each thread.
116#
117# Views:
118#
119#	Most of the tables have views for more friendly display.  The views are:
120#
121#		calls_view
122#		call_paths_view
123#		comm_threads_view
124#		dsos_view
125#		machines_view
126#		samples_view
127#		symbols_view
128#		threads_view
129#
130# More examples of browsing the database with psql:
131#   Note that some of the examples are not the most optimal SQL query.
132#   Note that call information is only available if the script's 'calls' option has been used.
133#
134#	Top 10 function calls (not aggregated by symbol):
135#
136#		SELECT * FROM calls_view ORDER BY elapsed_time DESC LIMIT 10;
137#
138#	Top 10 function calls (aggregated by symbol):
139#
140#		SELECT symbol_id,(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,
141#			SUM(elapsed_time) AS tot_elapsed_time,SUM(branch_count) AS tot_branch_count
142#			FROM calls_view GROUP BY symbol_id ORDER BY tot_elapsed_time DESC LIMIT 10;
143#
144#		Note that the branch count gives a rough estimation of cpu usage, so functions
145#		that took a long time but have a relatively low branch count must have spent time
146#		waiting.
147#
148#	Find symbols by pattern matching on part of the name (e.g. names containing 'alloc'):
149#
150#		SELECT * FROM symbols_view WHERE name LIKE '%alloc%';
151#
152#	Top 10 function calls for a specific symbol (e.g. whose symbol_id is 187):
153#
154#		SELECT * FROM calls_view WHERE symbol_id = 187 ORDER BY elapsed_time DESC LIMIT 10;
155#
156#	Show function calls made by function in the same context (i.e. same call path) (e.g. one with call_path_id 254):
157#
158#		SELECT * FROM calls_view WHERE parent_call_path_id = 254;
159#
160#	Show branches made during a function call (e.g. where call_id is 29357 and return_id is 29370 and tid is 29670)
161#
162#		SELECT * FROM samples_view WHERE id >= 29357 AND id <= 29370 AND tid = 29670 AND event LIKE 'branches%';
163#
164#	Show transactions:
165#
166#		SELECT * FROM samples_view WHERE event = 'transactions';
167#
168#		Note transaction start has 'in_tx' true whereas, transaction end has 'in_tx' false.
169#		Transaction aborts have branch_type_name 'transaction abort'
170#
171#	Show transaction aborts:
172#
173#		SELECT * FROM samples_view WHERE event = 'transactions' AND branch_type_name = 'transaction abort';
174#
175# To print a call stack requires walking the call_paths table.  For example this python script:
176#   #!/usr/bin/python2
177#
178#   import sys
179#   from PySide.QtSql import *
180#
181#   if __name__ == '__main__':
182#           if (len(sys.argv) < 3):
183#                   print >> sys.stderr, "Usage is: printcallstack.py <database name> <call_path_id>"
184#                   raise Exception("Too few arguments")
185#           dbname = sys.argv[1]
186#           call_path_id = sys.argv[2]
187#           db = QSqlDatabase.addDatabase('QPSQL')
188#           db.setDatabaseName(dbname)
189#           if not db.open():
190#                   raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text())
191#           query = QSqlQuery(db)
192#           print "    id          ip  symbol_id  symbol                          dso_id  dso_short_name"
193#           while call_path_id != 0 and call_path_id != 1:
194#                   ret = query.exec_('SELECT * FROM call_paths_view WHERE id = ' + str(call_path_id))
195#                   if not ret:
196#                           raise Exception("Query failed: " + query.lastError().text())
197#                   if not query.next():
198#                           raise Exception("Query failed")
199#                   print "{0:>6}  {1:>10}  {2:>9}  {3:<30}  {4:>6}  {5:<30}".format(query.value(0), query.value(1), query.value(2), query.value(3), query.value(4), query.value(5))
200#                   call_path_id = query.value(6)
201
202from PySide.QtSql import *
203
204if sys.version_info < (3, 0):
205	def toserverstr(str):
206		return str
207	def toclientstr(str):
208		return str
209else:
210	# Assume UTF-8 server_encoding and client_encoding
211	def toserverstr(str):
212		return bytes(str, "UTF_8")
213	def toclientstr(str):
214		return bytes(str, "UTF_8")
215
216# Need to access PostgreSQL C library directly to use COPY FROM STDIN
217from ctypes import *
218libpq = CDLL("libpq.so.5")
219PQconnectdb = libpq.PQconnectdb
220PQconnectdb.restype = c_void_p
221PQconnectdb.argtypes = [ c_char_p ]
222PQfinish = libpq.PQfinish
223PQfinish.argtypes = [ c_void_p ]
224PQstatus = libpq.PQstatus
225PQstatus.restype = c_int
226PQstatus.argtypes = [ c_void_p ]
227PQexec = libpq.PQexec
228PQexec.restype = c_void_p
229PQexec.argtypes = [ c_void_p, c_char_p ]
230PQresultStatus = libpq.PQresultStatus
231PQresultStatus.restype = c_int
232PQresultStatus.argtypes = [ c_void_p ]
233PQputCopyData = libpq.PQputCopyData
234PQputCopyData.restype = c_int
235PQputCopyData.argtypes = [ c_void_p, c_void_p, c_int ]
236PQputCopyEnd = libpq.PQputCopyEnd
237PQputCopyEnd.restype = c_int
238PQputCopyEnd.argtypes = [ c_void_p, c_void_p ]
239
240sys.path.append(os.environ['PERF_EXEC_PATH'] + \
241	'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
242
243# These perf imports are not used at present
244#from perf_trace_context import *
245#from Core import *
246
247perf_db_export_mode = True
248perf_db_export_calls = False
249perf_db_export_callchains = False
250
251def printerr(*args, **kw_args):
252	print(*args, file=sys.stderr, **kw_args)
253
254def usage():
255	printerr("Usage is: export-to-postgresql.py <database name> [<columns>] [<calls>] [<callchains>]")
256	printerr("where:	columns		'all' or 'branches'")
257	printerr("		calls		'calls' => create calls and call_paths table")
258	printerr("		callchains	'callchains' => create call_paths table")
259	raise Exception("Too few arguments")
260
261if (len(sys.argv) < 2):
262	usage()
263
264dbname = sys.argv[1]
265
266if (len(sys.argv) >= 3):
267	columns = sys.argv[2]
268else:
269	columns = "all"
270
271if columns not in ("all", "branches"):
272	usage()
273
274branches = (columns == "branches")
275
276for i in range(3,len(sys.argv)):
277	if (sys.argv[i] == "calls"):
278		perf_db_export_calls = True
279	elif (sys.argv[i] == "callchains"):
280		perf_db_export_callchains = True
281	else:
282		usage()
283
284output_dir_name = os.getcwd() + "/" + dbname + "-perf-data"
285os.mkdir(output_dir_name)
286
287def do_query(q, s):
288	if (q.exec_(s)):
289		return
290	raise Exception("Query failed: " + q.lastError().text())
291
292print(datetime.datetime.today(), "Creating database...")
293
294db = QSqlDatabase.addDatabase('QPSQL')
295query = QSqlQuery(db)
296db.setDatabaseName('postgres')
297db.open()
298try:
299	do_query(query, 'CREATE DATABASE ' + dbname)
300except:
301	os.rmdir(output_dir_name)
302	raise
303query.finish()
304query.clear()
305db.close()
306
307db.setDatabaseName(dbname)
308db.open()
309
310query = QSqlQuery(db)
311do_query(query, 'SET client_min_messages TO WARNING')
312
313do_query(query, 'CREATE TABLE selected_events ('
314		'id		bigint		NOT NULL,'
315		'name		varchar(80))')
316do_query(query, 'CREATE TABLE machines ('
317		'id		bigint		NOT NULL,'
318		'pid		integer,'
319		'root_dir 	varchar(4096))')
320do_query(query, 'CREATE TABLE threads ('
321		'id		bigint		NOT NULL,'
322		'machine_id	bigint,'
323		'process_id	bigint,'
324		'pid		integer,'
325		'tid		integer)')
326do_query(query, 'CREATE TABLE comms ('
327		'id		bigint		NOT NULL,'
328		'comm		varchar(16))')
329do_query(query, 'CREATE TABLE comm_threads ('
330		'id		bigint		NOT NULL,'
331		'comm_id	bigint,'
332		'thread_id	bigint)')
333do_query(query, 'CREATE TABLE dsos ('
334		'id		bigint		NOT NULL,'
335		'machine_id	bigint,'
336		'short_name	varchar(256),'
337		'long_name	varchar(4096),'
338		'build_id	varchar(64))')
339do_query(query, 'CREATE TABLE symbols ('
340		'id		bigint		NOT NULL,'
341		'dso_id		bigint,'
342		'sym_start	bigint,'
343		'sym_end	bigint,'
344		'binding	integer,'
345		'name		varchar(2048))')
346do_query(query, 'CREATE TABLE branch_types ('
347		'id		integer		NOT NULL,'
348		'name		varchar(80))')
349
350if branches:
351	do_query(query, 'CREATE TABLE samples ('
352		'id		bigint		NOT NULL,'
353		'evsel_id	bigint,'
354		'machine_id	bigint,'
355		'thread_id	bigint,'
356		'comm_id	bigint,'
357		'dso_id		bigint,'
358		'symbol_id	bigint,'
359		'sym_offset	bigint,'
360		'ip		bigint,'
361		'time		bigint,'
362		'cpu		integer,'
363		'to_dso_id	bigint,'
364		'to_symbol_id	bigint,'
365		'to_sym_offset	bigint,'
366		'to_ip		bigint,'
367		'branch_type	integer,'
368		'in_tx		boolean,'
369		'call_path_id	bigint)')
370else:
371	do_query(query, 'CREATE TABLE samples ('
372		'id		bigint		NOT NULL,'
373		'evsel_id	bigint,'
374		'machine_id	bigint,'
375		'thread_id	bigint,'
376		'comm_id	bigint,'
377		'dso_id		bigint,'
378		'symbol_id	bigint,'
379		'sym_offset	bigint,'
380		'ip		bigint,'
381		'time		bigint,'
382		'cpu		integer,'
383		'to_dso_id	bigint,'
384		'to_symbol_id	bigint,'
385		'to_sym_offset	bigint,'
386		'to_ip		bigint,'
387		'period		bigint,'
388		'weight		bigint,'
389		'transaction	bigint,'
390		'data_src	bigint,'
391		'branch_type	integer,'
392		'in_tx		boolean,'
393		'call_path_id	bigint)')
394
395if perf_db_export_calls or perf_db_export_callchains:
396	do_query(query, 'CREATE TABLE call_paths ('
397		'id		bigint		NOT NULL,'
398		'parent_id	bigint,'
399		'symbol_id	bigint,'
400		'ip		bigint)')
401if perf_db_export_calls:
402	do_query(query, 'CREATE TABLE calls ('
403		'id		bigint		NOT NULL,'
404		'thread_id	bigint,'
405		'comm_id	bigint,'
406		'call_path_id	bigint,'
407		'call_time	bigint,'
408		'return_time	bigint,'
409		'branch_count	bigint,'
410		'call_id	bigint,'
411		'return_id	bigint,'
412		'parent_call_path_id	bigint,'
413		'flags		integer,'
414		'parent_id	bigint)')
415
416do_query(query, 'CREATE VIEW machines_view AS '
417	'SELECT '
418		'id,'
419		'pid,'
420		'root_dir,'
421		'CASE WHEN id=0 THEN \'unknown\' WHEN pid=-1 THEN \'host\' ELSE \'guest\' END AS host_or_guest'
422	' FROM machines')
423
424do_query(query, 'CREATE VIEW dsos_view AS '
425	'SELECT '
426		'id,'
427		'machine_id,'
428		'(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
429		'short_name,'
430		'long_name,'
431		'build_id'
432	' FROM dsos')
433
434do_query(query, 'CREATE VIEW symbols_view AS '
435	'SELECT '
436		'id,'
437		'name,'
438		'(SELECT short_name FROM dsos WHERE id=dso_id) AS dso,'
439		'dso_id,'
440		'sym_start,'
441		'sym_end,'
442		'CASE WHEN binding=0 THEN \'local\' WHEN binding=1 THEN \'global\' ELSE \'weak\' END AS binding'
443	' FROM symbols')
444
445do_query(query, 'CREATE VIEW threads_view AS '
446	'SELECT '
447		'id,'
448		'machine_id,'
449		'(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
450		'process_id,'
451		'pid,'
452		'tid'
453	' FROM threads')
454
455do_query(query, 'CREATE VIEW comm_threads_view AS '
456	'SELECT '
457		'comm_id,'
458		'(SELECT comm FROM comms WHERE id = comm_id) AS command,'
459		'thread_id,'
460		'(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
461		'(SELECT tid FROM threads WHERE id = thread_id) AS tid'
462	' FROM comm_threads')
463
464if perf_db_export_calls or perf_db_export_callchains:
465	do_query(query, 'CREATE VIEW call_paths_view AS '
466		'SELECT '
467			'c.id,'
468			'to_hex(c.ip) AS ip,'
469			'c.symbol_id,'
470			'(SELECT name FROM symbols WHERE id = c.symbol_id) AS symbol,'
471			'(SELECT dso_id FROM symbols WHERE id = c.symbol_id) AS dso_id,'
472			'(SELECT dso FROM symbols_view  WHERE id = c.symbol_id) AS dso_short_name,'
473			'c.parent_id,'
474			'to_hex(p.ip) AS parent_ip,'
475			'p.symbol_id AS parent_symbol_id,'
476			'(SELECT name FROM symbols WHERE id = p.symbol_id) AS parent_symbol,'
477			'(SELECT dso_id FROM symbols WHERE id = p.symbol_id) AS parent_dso_id,'
478			'(SELECT dso FROM symbols_view  WHERE id = p.symbol_id) AS parent_dso_short_name'
479		' FROM call_paths c INNER JOIN call_paths p ON p.id = c.parent_id')
480if perf_db_export_calls:
481	do_query(query, 'CREATE VIEW calls_view AS '
482		'SELECT '
483			'calls.id,'
484			'thread_id,'
485			'(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
486			'(SELECT tid FROM threads WHERE id = thread_id) AS tid,'
487			'(SELECT comm FROM comms WHERE id = comm_id) AS command,'
488			'call_path_id,'
489			'to_hex(ip) AS ip,'
490			'symbol_id,'
491			'(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
492			'call_time,'
493			'return_time,'
494			'return_time - call_time AS elapsed_time,'
495			'branch_count,'
496			'call_id,'
497			'return_id,'
498			'CASE WHEN flags=0 THEN \'\' WHEN flags=1 THEN \'no call\' WHEN flags=2 THEN \'no return\' WHEN flags=3 THEN \'no call/return\' WHEN flags=6 THEN \'jump\' ELSE CAST ( flags AS VARCHAR(6) ) END AS flags,'
499			'parent_call_path_id,'
500			'calls.parent_id'
501		' FROM calls INNER JOIN call_paths ON call_paths.id = call_path_id')
502
503do_query(query, 'CREATE VIEW samples_view AS '
504	'SELECT '
505		'id,'
506		'time,'
507		'cpu,'
508		'(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
509		'(SELECT tid FROM threads WHERE id = thread_id) AS tid,'
510		'(SELECT comm FROM comms WHERE id = comm_id) AS command,'
511		'(SELECT name FROM selected_events WHERE id = evsel_id) AS event,'
512		'to_hex(ip) AS ip_hex,'
513		'(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
514		'sym_offset,'
515		'(SELECT short_name FROM dsos WHERE id = dso_id) AS dso_short_name,'
516		'to_hex(to_ip) AS to_ip_hex,'
517		'(SELECT name FROM symbols WHERE id = to_symbol_id) AS to_symbol,'
518		'to_sym_offset,'
519		'(SELECT short_name FROM dsos WHERE id = to_dso_id) AS to_dso_short_name,'
520		'(SELECT name FROM branch_types WHERE id = branch_type) AS branch_type_name,'
521		'in_tx'
522	' FROM samples')
523
524
525file_header = struct.pack("!11sii", b"PGCOPY\n\377\r\n\0", 0, 0)
526file_trailer = b"\377\377"
527
528def open_output_file(file_name):
529	path_name = output_dir_name + "/" + file_name
530	file = open(path_name, "wb+")
531	file.write(file_header)
532	return file
533
534def close_output_file(file):
535	file.write(file_trailer)
536	file.close()
537
538def copy_output_file_direct(file, table_name):
539	close_output_file(file)
540	sql = "COPY " + table_name + " FROM '" + file.name + "' (FORMAT 'binary')"
541	do_query(query, sql)
542
543# Use COPY FROM STDIN because security may prevent postgres from accessing the files directly
544def copy_output_file(file, table_name):
545	conn = PQconnectdb(toclientstr("dbname = " + dbname))
546	if (PQstatus(conn)):
547		raise Exception("COPY FROM STDIN PQconnectdb failed")
548	file.write(file_trailer)
549	file.seek(0)
550	sql = "COPY " + table_name + " FROM STDIN (FORMAT 'binary')"
551	res = PQexec(conn, toclientstr(sql))
552	if (PQresultStatus(res) != 4):
553		raise Exception("COPY FROM STDIN PQexec failed")
554	data = file.read(65536)
555	while (len(data)):
556		ret = PQputCopyData(conn, data, len(data))
557		if (ret != 1):
558			raise Exception("COPY FROM STDIN PQputCopyData failed, error " + str(ret))
559		data = file.read(65536)
560	ret = PQputCopyEnd(conn, None)
561	if (ret != 1):
562		raise Exception("COPY FROM STDIN PQputCopyEnd failed, error " + str(ret))
563	PQfinish(conn)
564
565def remove_output_file(file):
566	name = file.name
567	file.close()
568	os.unlink(name)
569
570evsel_file		= open_output_file("evsel_table.bin")
571machine_file		= open_output_file("machine_table.bin")
572thread_file		= open_output_file("thread_table.bin")
573comm_file		= open_output_file("comm_table.bin")
574comm_thread_file	= open_output_file("comm_thread_table.bin")
575dso_file		= open_output_file("dso_table.bin")
576symbol_file		= open_output_file("symbol_table.bin")
577branch_type_file	= open_output_file("branch_type_table.bin")
578sample_file		= open_output_file("sample_table.bin")
579if perf_db_export_calls or perf_db_export_callchains:
580	call_path_file		= open_output_file("call_path_table.bin")
581if perf_db_export_calls:
582	call_file		= open_output_file("call_table.bin")
583
584def trace_begin():
585	print(datetime.datetime.today(), "Writing to intermediate files...")
586	# id == 0 means unknown.  It is easier to create records for them than replace the zeroes with NULLs
587	evsel_table(0, "unknown")
588	machine_table(0, 0, "unknown")
589	thread_table(0, 0, 0, -1, -1)
590	comm_table(0, "unknown")
591	dso_table(0, 0, "unknown", "unknown", "")
592	symbol_table(0, 0, 0, 0, 0, "unknown")
593	sample_table(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
594	if perf_db_export_calls or perf_db_export_callchains:
595		call_path_table(0, 0, 0, 0)
596		call_return_table(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
597
598unhandled_count = 0
599
600def trace_end():
601	print(datetime.datetime.today(), "Copying to database...")
602	copy_output_file(evsel_file,		"selected_events")
603	copy_output_file(machine_file,		"machines")
604	copy_output_file(thread_file,		"threads")
605	copy_output_file(comm_file,		"comms")
606	copy_output_file(comm_thread_file,	"comm_threads")
607	copy_output_file(dso_file,		"dsos")
608	copy_output_file(symbol_file,		"symbols")
609	copy_output_file(branch_type_file,	"branch_types")
610	copy_output_file(sample_file,		"samples")
611	if perf_db_export_calls or perf_db_export_callchains:
612		copy_output_file(call_path_file,	"call_paths")
613	if perf_db_export_calls:
614		copy_output_file(call_file,		"calls")
615
616	print(datetime.datetime.today(), "Removing intermediate files...")
617	remove_output_file(evsel_file)
618	remove_output_file(machine_file)
619	remove_output_file(thread_file)
620	remove_output_file(comm_file)
621	remove_output_file(comm_thread_file)
622	remove_output_file(dso_file)
623	remove_output_file(symbol_file)
624	remove_output_file(branch_type_file)
625	remove_output_file(sample_file)
626	if perf_db_export_calls or perf_db_export_callchains:
627		remove_output_file(call_path_file)
628	if perf_db_export_calls:
629		remove_output_file(call_file)
630	os.rmdir(output_dir_name)
631	print(datetime.datetime.today(), "Adding primary keys")
632	do_query(query, 'ALTER TABLE selected_events ADD PRIMARY KEY (id)')
633	do_query(query, 'ALTER TABLE machines        ADD PRIMARY KEY (id)')
634	do_query(query, 'ALTER TABLE threads         ADD PRIMARY KEY (id)')
635	do_query(query, 'ALTER TABLE comms           ADD PRIMARY KEY (id)')
636	do_query(query, 'ALTER TABLE comm_threads    ADD PRIMARY KEY (id)')
637	do_query(query, 'ALTER TABLE dsos            ADD PRIMARY KEY (id)')
638	do_query(query, 'ALTER TABLE symbols         ADD PRIMARY KEY (id)')
639	do_query(query, 'ALTER TABLE branch_types    ADD PRIMARY KEY (id)')
640	do_query(query, 'ALTER TABLE samples         ADD PRIMARY KEY (id)')
641	if perf_db_export_calls or perf_db_export_callchains:
642		do_query(query, 'ALTER TABLE call_paths      ADD PRIMARY KEY (id)')
643	if perf_db_export_calls:
644		do_query(query, 'ALTER TABLE calls           ADD PRIMARY KEY (id)')
645
646	print(datetime.datetime.today(), "Adding foreign keys")
647	do_query(query, 'ALTER TABLE threads '
648					'ADD CONSTRAINT machinefk  FOREIGN KEY (machine_id)   REFERENCES machines   (id),'
649					'ADD CONSTRAINT processfk  FOREIGN KEY (process_id)   REFERENCES threads    (id)')
650	do_query(query, 'ALTER TABLE comm_threads '
651					'ADD CONSTRAINT commfk     FOREIGN KEY (comm_id)      REFERENCES comms      (id),'
652					'ADD CONSTRAINT threadfk   FOREIGN KEY (thread_id)    REFERENCES threads    (id)')
653	do_query(query, 'ALTER TABLE dsos '
654					'ADD CONSTRAINT machinefk  FOREIGN KEY (machine_id)   REFERENCES machines   (id)')
655	do_query(query, 'ALTER TABLE symbols '
656					'ADD CONSTRAINT dsofk      FOREIGN KEY (dso_id)       REFERENCES dsos       (id)')
657	do_query(query, 'ALTER TABLE samples '
658					'ADD CONSTRAINT evselfk    FOREIGN KEY (evsel_id)     REFERENCES selected_events (id),'
659					'ADD CONSTRAINT machinefk  FOREIGN KEY (machine_id)   REFERENCES machines   (id),'
660					'ADD CONSTRAINT threadfk   FOREIGN KEY (thread_id)    REFERENCES threads    (id),'
661					'ADD CONSTRAINT commfk     FOREIGN KEY (comm_id)      REFERENCES comms      (id),'
662					'ADD CONSTRAINT dsofk      FOREIGN KEY (dso_id)       REFERENCES dsos       (id),'
663					'ADD CONSTRAINT symbolfk   FOREIGN KEY (symbol_id)    REFERENCES symbols    (id),'
664					'ADD CONSTRAINT todsofk    FOREIGN KEY (to_dso_id)    REFERENCES dsos       (id),'
665					'ADD CONSTRAINT tosymbolfk FOREIGN KEY (to_symbol_id) REFERENCES symbols    (id)')
666	if perf_db_export_calls or perf_db_export_callchains:
667		do_query(query, 'ALTER TABLE call_paths '
668					'ADD CONSTRAINT parentfk    FOREIGN KEY (parent_id)    REFERENCES call_paths (id),'
669					'ADD CONSTRAINT symbolfk    FOREIGN KEY (symbol_id)    REFERENCES symbols    (id)')
670	if perf_db_export_calls:
671		do_query(query, 'ALTER TABLE calls '
672					'ADD CONSTRAINT threadfk    FOREIGN KEY (thread_id)    REFERENCES threads    (id),'
673					'ADD CONSTRAINT commfk      FOREIGN KEY (comm_id)      REFERENCES comms      (id),'
674					'ADD CONSTRAINT call_pathfk FOREIGN KEY (call_path_id) REFERENCES call_paths (id),'
675					'ADD CONSTRAINT callfk      FOREIGN KEY (call_id)      REFERENCES samples    (id),'
676					'ADD CONSTRAINT returnfk    FOREIGN KEY (return_id)    REFERENCES samples    (id),'
677					'ADD CONSTRAINT parent_call_pathfk FOREIGN KEY (parent_call_path_id) REFERENCES call_paths (id)')
678		do_query(query, 'CREATE INDEX pcpid_idx ON calls (parent_call_path_id)')
679		do_query(query, 'CREATE INDEX pid_idx ON calls (parent_id)')
680
681	if (unhandled_count):
682		print(datetime.datetime.today(), "Warning: ", unhandled_count, " unhandled events")
683	print(datetime.datetime.today(), "Done")
684
685def trace_unhandled(event_name, context, event_fields_dict):
686	global unhandled_count
687	unhandled_count += 1
688
689def sched__sched_switch(*x):
690	pass
691
692def evsel_table(evsel_id, evsel_name, *x):
693	evsel_name = toserverstr(evsel_name)
694	n = len(evsel_name)
695	fmt = "!hiqi" + str(n) + "s"
696	value = struct.pack(fmt, 2, 8, evsel_id, n, evsel_name)
697	evsel_file.write(value)
698
699def machine_table(machine_id, pid, root_dir, *x):
700	root_dir = toserverstr(root_dir)
701	n = len(root_dir)
702	fmt = "!hiqiii" + str(n) + "s"
703	value = struct.pack(fmt, 3, 8, machine_id, 4, pid, n, root_dir)
704	machine_file.write(value)
705
706def thread_table(thread_id, machine_id, process_id, pid, tid, *x):
707	value = struct.pack("!hiqiqiqiiii", 5, 8, thread_id, 8, machine_id, 8, process_id, 4, pid, 4, tid)
708	thread_file.write(value)
709
710def comm_table(comm_id, comm_str, *x):
711	comm_str = toserverstr(comm_str)
712	n = len(comm_str)
713	fmt = "!hiqi" + str(n) + "s"
714	value = struct.pack(fmt, 2, 8, comm_id, n, comm_str)
715	comm_file.write(value)
716
717def comm_thread_table(comm_thread_id, comm_id, thread_id, *x):
718	fmt = "!hiqiqiq"
719	value = struct.pack(fmt, 3, 8, comm_thread_id, 8, comm_id, 8, thread_id)
720	comm_thread_file.write(value)
721
722def dso_table(dso_id, machine_id, short_name, long_name, build_id, *x):
723	short_name = toserverstr(short_name)
724	long_name = toserverstr(long_name)
725	build_id = toserverstr(build_id)
726	n1 = len(short_name)
727	n2 = len(long_name)
728	n3 = len(build_id)
729	fmt = "!hiqiqi" + str(n1) + "si"  + str(n2) + "si" + str(n3) + "s"
730	value = struct.pack(fmt, 5, 8, dso_id, 8, machine_id, n1, short_name, n2, long_name, n3, build_id)
731	dso_file.write(value)
732
733def symbol_table(symbol_id, dso_id, sym_start, sym_end, binding, symbol_name, *x):
734	symbol_name = toserverstr(symbol_name)
735	n = len(symbol_name)
736	fmt = "!hiqiqiqiqiii" + str(n) + "s"
737	value = struct.pack(fmt, 6, 8, symbol_id, 8, dso_id, 8, sym_start, 8, sym_end, 4, binding, n, symbol_name)
738	symbol_file.write(value)
739
740def branch_type_table(branch_type, name, *x):
741	name = toserverstr(name)
742	n = len(name)
743	fmt = "!hiii" + str(n) + "s"
744	value = struct.pack(fmt, 2, 4, branch_type, n, name)
745	branch_type_file.write(value)
746
747def sample_table(sample_id, evsel_id, machine_id, thread_id, comm_id, dso_id, symbol_id, sym_offset, ip, time, cpu, to_dso_id, to_symbol_id, to_sym_offset, to_ip, period, weight, transaction, data_src, branch_type, in_tx, call_path_id, *x):
748	if branches:
749		value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiiiBiq", 18, 8, sample_id, 8, evsel_id, 8, machine_id, 8, thread_id, 8, comm_id, 8, dso_id, 8, symbol_id, 8, sym_offset, 8, ip, 8, time, 4, cpu, 8, to_dso_id, 8, to_symbol_id, 8, to_sym_offset, 8, to_ip, 4, branch_type, 1, in_tx, 8, call_path_id)
750	else:
751		value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiqiqiqiqiiiBiq", 22, 8, sample_id, 8, evsel_id, 8, machine_id, 8, thread_id, 8, comm_id, 8, dso_id, 8, symbol_id, 8, sym_offset, 8, ip, 8, time, 4, cpu, 8, to_dso_id, 8, to_symbol_id, 8, to_sym_offset, 8, to_ip, 8, period, 8, weight, 8, transaction, 8, data_src, 4, branch_type, 1, in_tx, 8, call_path_id)
752	sample_file.write(value)
753
754def call_path_table(cp_id, parent_id, symbol_id, ip, *x):
755	fmt = "!hiqiqiqiq"
756	value = struct.pack(fmt, 4, 8, cp_id, 8, parent_id, 8, symbol_id, 8, ip)
757	call_path_file.write(value)
758
759def call_return_table(cr_id, thread_id, comm_id, call_path_id, call_time, return_time, branch_count, call_id, return_id, parent_call_path_id, flags, parent_id, *x):
760	fmt = "!hiqiqiqiqiqiqiqiqiqiqiiiq"
761	value = struct.pack(fmt, 12, 8, cr_id, 8, thread_id, 8, comm_id, 8, call_path_id, 8, call_time, 8, return_time, 8, branch_count, 8, call_id, 8, return_id, 8, parent_call_path_id, 4, flags, 8, parent_id)
762	call_file.write(value)
763