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