1 # export-to-postgresql.py: export perf data to a postgresql database
2 # Copyright (c) 2014, Intel Corporation.
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.
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
13 from __future__ import print_function
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.
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:
30 # $ sudo yum install postgresql postgresql-server qt-postgresql
31 # $ sudo su - postgres -c initdb
32 # $ sudo service postgresql start
33 # $ sudo su - postgres
34 # $ createuser -s <your user id here> # Older versions may not support -s, in which case answer the prompt below:
35 # Shall the new role be a superuser? (y/n) y
36 # $ sudo yum install python-pyside
38 # Alternately, to use Python3 and/or pyside 2, one of the following:
39 # $ sudo yum install python3-pyside
40 # $ pip install --user PySide2
41 # $ pip3 install --user PySide2
45 # $ sudo apt-get install postgresql
46 # $ sudo su - postgres
47 # $ createuser -s <your user id here>
48 # $ sudo apt-get install python-pyside.qtsql libqt4-sql-psql
50 # Alternately, to use Python3 and/or pyside 2, one of the following:
52 # $ sudo apt-get install python3-pyside.qtsql libqt4-sql-psql
53 # $ sudo apt-get install python-pyside2.qtsql libqt5sql5-psql
54 # $ sudo apt-get install python3-pyside2.qtsql libqt5sql5-psql
56 # An example of using this script with Intel PT:
58 # $ perf record -e intel_pt//u ls
59 # $ perf script -s ~/libexec/perf-core/scripts/python/export-to-postgresql.py pt_example branches calls
60 # 2015-05-29 12:49:23.464364 Creating database...
61 # 2015-05-29 12:49:26.281717 Writing to intermediate files...
62 # 2015-05-29 12:49:27.190383 Copying to database...
63 # 2015-05-29 12:49:28.140451 Removing intermediate files...
64 # 2015-05-29 12:49:28.147451 Adding primary keys
65 # 2015-05-29 12:49:28.655683 Adding foreign keys
66 # 2015-05-29 12:49:29.365350 Done
68 # To browse the database, psql can be used e.g.
71 # pt_example=# select * from samples_view where id < 100;
73 # pt_example=# \d+ samples_view
76 # An example of using the database is provided by the script
77 # exported-sql-viewer.py. Refer to that script for details.
81 # The tables largely correspond to perf tools' data structures. They are largely self-explanatory.
85 # 'samples' is the main table. It represents what instruction was executing at a point in time
86 # when something (a selected event) happened. The memory address is the instruction pointer or 'ip'.
90 # 'calls' represents function calls and is related to 'samples' by 'call_id' and 'return_id'.
91 # 'calls' is only created when the 'calls' option to this script is specified.
95 # 'call_paths' represents all the call stacks. Each 'call' has an associated record in 'call_paths'.
96 # 'calls_paths' is only created when the 'calls' option to this script is specified.
100 # 'branch_types' provides descriptions for each type of branch.
104 # 'comm_threads' shows how 'comms' relates to 'threads'.
108 # 'comms' contains a record for each 'comm' - the name given to the executable that is running.
112 # 'dsos' contains a record for each executable file or library.
116 # 'machines' can be used to distinguish virtual machines if virtualization is supported.
120 # 'selected_events' contains a record for each kind of event that has been sampled.
124 # 'symbols' contains a record for each symbol. Only symbols that have samples are present.
128 # 'threads' contains a record for each thread.
132 # Most of the tables have views for more friendly display. The views are:
143 # More examples of browsing the database with psql:
144 # Note that some of the examples are not the most optimal SQL query.
145 # Note that call information is only available if the script's 'calls' option has been used.
147 # Top 10 function calls (not aggregated by symbol):
149 # SELECT * FROM calls_view ORDER BY elapsed_time DESC LIMIT 10;
151 # Top 10 function calls (aggregated by symbol):
153 # SELECT symbol_id,(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,
154 # SUM(elapsed_time) AS tot_elapsed_time,SUM(branch_count) AS tot_branch_count
155 # FROM calls_view GROUP BY symbol_id ORDER BY tot_elapsed_time DESC LIMIT 10;
157 # Note that the branch count gives a rough estimation of cpu usage, so functions
158 # that took a long time but have a relatively low branch count must have spent time
161 # Find symbols by pattern matching on part of the name (e.g. names containing 'alloc'):
163 # SELECT * FROM symbols_view WHERE name LIKE '%alloc%';
165 # Top 10 function calls for a specific symbol (e.g. whose symbol_id is 187):
167 # SELECT * FROM calls_view WHERE symbol_id = 187 ORDER BY elapsed_time DESC LIMIT 10;
169 # Show function calls made by function in the same context (i.e. same call path) (e.g. one with call_path_id 254):
171 # SELECT * FROM calls_view WHERE parent_call_path_id = 254;
173 # Show branches made during a function call (e.g. where call_id is 29357 and return_id is 29370 and tid is 29670)
175 # SELECT * FROM samples_view WHERE id >= 29357 AND id <= 29370 AND tid = 29670 AND event LIKE 'branches%';
179 # SELECT * FROM samples_view WHERE event = 'transactions';
181 # Note transaction start has 'in_tx' true whereas, transaction end has 'in_tx' false.
182 # Transaction aborts have branch_type_name 'transaction abort'
184 # Show transaction aborts:
186 # SELECT * FROM samples_view WHERE event = 'transactions' AND branch_type_name = 'transaction abort';
188 # To print a call stack requires walking the call_paths table. For example this python script:
192 # from PySide.QtSql import *
194 # if __name__ == '__main__':
195 # if (len(sys.argv) < 3):
196 # print >> sys.stderr, "Usage is: printcallstack.py <database name> <call_path_id>"
197 # raise Exception("Too few arguments")
198 # dbname = sys.argv[1]
199 # call_path_id = sys.argv[2]
200 # db = QSqlDatabase.addDatabase('QPSQL')
201 # db.setDatabaseName(dbname)
203 # raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text())
204 # query = QSqlQuery(db)
205 # print " id ip symbol_id symbol dso_id dso_short_name"
206 # while call_path_id != 0 and call_path_id != 1:
207 # ret = query.exec_('SELECT * FROM call_paths_view WHERE id = ' + str(call_path_id))
209 # raise Exception("Query failed: " + query.lastError().text())
210 # if not query.next():
211 # raise Exception("Query failed")
212 # 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))
213 # call_path_id = query.value(6)
215 pyside_version_1 = True
216 if not "pyside-version-1" in sys.argv:
218 from PySide2.QtSql import *
219 pyside_version_1 = False
224 from PySide.QtSql import *
226 if sys.version_info < (3, 0):
227 def toserverstr(str):
229 def toclientstr(str):
232 # Assume UTF-8 server_encoding and client_encoding
233 def toserverstr(str):
234 return bytes(str, "UTF_8")
235 def toclientstr(str):
236 return bytes(str, "UTF_8")
238 # Need to access PostgreSQL C library directly to use COPY FROM STDIN
240 libpq = CDLL("libpq.so.5")
241 PQconnectdb = libpq.PQconnectdb
242 PQconnectdb.restype = c_void_p
243 PQconnectdb.argtypes = [ c_char_p ]
244 PQfinish = libpq.PQfinish
245 PQfinish.argtypes = [ c_void_p ]
246 PQstatus = libpq.PQstatus
247 PQstatus.restype = c_int
248 PQstatus.argtypes = [ c_void_p ]
249 PQexec = libpq.PQexec
250 PQexec.restype = c_void_p
251 PQexec.argtypes = [ c_void_p, c_char_p ]
252 PQresultStatus = libpq.PQresultStatus
253 PQresultStatus.restype = c_int
254 PQresultStatus.argtypes = [ c_void_p ]
255 PQputCopyData = libpq.PQputCopyData
256 PQputCopyData.restype = c_int
257 PQputCopyData.argtypes = [ c_void_p, c_void_p, c_int ]
258 PQputCopyEnd = libpq.PQputCopyEnd
259 PQputCopyEnd.restype = c_int
260 PQputCopyEnd.argtypes = [ c_void_p, c_void_p ]
262 sys.path.append(os.environ['PERF_EXEC_PATH'] + \
263 '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
265 # These perf imports are not used at present
266 #from perf_trace_context import *
269 perf_db_export_mode = True
270 perf_db_export_calls = False
271 perf_db_export_callchains = False
273 def printerr(*args, **kw_args):
274 print(*args, file=sys.stderr, **kw_args)
276 def printdate(*args, **kw_args):
277 print(datetime.datetime.today(), *args, sep=' ', **kw_args)
280 printerr("Usage is: export-to-postgresql.py <database name> [<columns>] [<calls>] [<callchains>] [<pyside-version-1>]");
281 printerr("where: columns 'all' or 'branches'");
282 printerr(" calls 'calls' => create calls and call_paths table");
283 printerr(" callchains 'callchains' => create call_paths table");
284 printerr(" pyside-version-1 'pyside-version-1' => use pyside version 1");
285 raise Exception("Too few or bad arguments")
287 if (len(sys.argv) < 2):
292 if (len(sys.argv) >= 3):
293 columns = sys.argv[2]
297 if columns not in ("all", "branches"):
300 branches = (columns == "branches")
302 for i in range(3,len(sys.argv)):
303 if (sys.argv[i] == "calls"):
304 perf_db_export_calls = True
305 elif (sys.argv[i] == "callchains"):
306 perf_db_export_callchains = True
307 elif (sys.argv[i] == "pyside-version-1"):
312 output_dir_name = os.getcwd() + "/" + dbname + "-perf-data"
313 os.mkdir(output_dir_name)
318 raise Exception("Query failed: " + q.lastError().text())
320 printdate("Creating database...")
322 db = QSqlDatabase.addDatabase('QPSQL')
323 query = QSqlQuery(db)
324 db.setDatabaseName('postgres')
327 do_query(query, 'CREATE DATABASE ' + dbname)
329 os.rmdir(output_dir_name)
335 db.setDatabaseName(dbname)
338 query = QSqlQuery(db)
339 do_query(query, 'SET client_min_messages TO WARNING')
341 do_query(query, 'CREATE TABLE selected_events ('
342 'id bigint NOT NULL,'
344 do_query(query, 'CREATE TABLE machines ('
345 'id bigint NOT NULL,'
347 'root_dir varchar(4096))')
348 do_query(query, 'CREATE TABLE threads ('
349 'id bigint NOT NULL,'
354 do_query(query, 'CREATE TABLE comms ('
355 'id bigint NOT NULL,'
357 do_query(query, 'CREATE TABLE comm_threads ('
358 'id bigint NOT NULL,'
361 do_query(query, 'CREATE TABLE dsos ('
362 'id bigint NOT NULL,'
364 'short_name varchar(256),'
365 'long_name varchar(4096),'
366 'build_id varchar(64))')
367 do_query(query, 'CREATE TABLE symbols ('
368 'id bigint NOT NULL,'
373 'name varchar(2048))')
374 do_query(query, 'CREATE TABLE branch_types ('
375 'id integer NOT NULL,'
379 do_query(query, 'CREATE TABLE samples ('
380 'id bigint NOT NULL,'
392 'to_symbol_id bigint,'
393 'to_sym_offset bigint,'
395 'branch_type integer,'
397 'call_path_id bigint,'
401 do_query(query, 'CREATE TABLE samples ('
402 'id bigint NOT NULL,'
414 'to_symbol_id bigint,'
415 'to_sym_offset bigint,'
419 'transaction bigint,'
421 'branch_type integer,'
423 'call_path_id bigint,'
427 if perf_db_export_calls or perf_db_export_callchains:
428 do_query(query, 'CREATE TABLE call_paths ('
429 'id bigint NOT NULL,'
433 if perf_db_export_calls:
434 do_query(query, 'CREATE TABLE calls ('
435 'id bigint NOT NULL,'
438 'call_path_id bigint,'
440 'return_time bigint,'
441 'branch_count bigint,'
444 'parent_call_path_id bigint,'
450 do_query(query, 'CREATE TABLE ptwrite ('
451 'id bigint NOT NULL,'
455 do_query(query, 'CREATE TABLE cbr ('
456 'id bigint NOT NULL,'
461 do_query(query, 'CREATE TABLE mwait ('
462 'id bigint NOT NULL,'
464 'extensions integer)')
466 do_query(query, 'CREATE TABLE pwre ('
467 'id bigint NOT NULL,'
472 do_query(query, 'CREATE TABLE exstop ('
473 'id bigint NOT NULL,'
476 do_query(query, 'CREATE TABLE pwrx ('
477 'id bigint NOT NULL,'
478 'deepest_cstate integer,'
479 'last_cstate integer,'
480 'wake_reason integer)')
482 do_query(query, 'CREATE VIEW machines_view AS '
487 'CASE WHEN id=0 THEN \'unknown\' WHEN pid=-1 THEN \'host\' ELSE \'guest\' END AS host_or_guest'
490 do_query(query, 'CREATE VIEW dsos_view AS '
494 '(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
500 do_query(query, 'CREATE VIEW symbols_view AS '
504 '(SELECT short_name FROM dsos WHERE id=dso_id) AS dso,'
508 'CASE WHEN binding=0 THEN \'local\' WHEN binding=1 THEN \'global\' ELSE \'weak\' END AS binding'
511 do_query(query, 'CREATE VIEW threads_view AS '
515 '(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
521 do_query(query, 'CREATE VIEW comm_threads_view AS '
524 '(SELECT comm FROM comms WHERE id = comm_id) AS command,'
526 '(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
527 '(SELECT tid FROM threads WHERE id = thread_id) AS tid'
528 ' FROM comm_threads')
530 if perf_db_export_calls or perf_db_export_callchains:
531 do_query(query, 'CREATE VIEW call_paths_view AS '
534 'to_hex(c.ip) AS ip,'
536 '(SELECT name FROM symbols WHERE id = c.symbol_id) AS symbol,'
537 '(SELECT dso_id FROM symbols WHERE id = c.symbol_id) AS dso_id,'
538 '(SELECT dso FROM symbols_view WHERE id = c.symbol_id) AS dso_short_name,'
540 'to_hex(p.ip) AS parent_ip,'
541 'p.symbol_id AS parent_symbol_id,'
542 '(SELECT name FROM symbols WHERE id = p.symbol_id) AS parent_symbol,'
543 '(SELECT dso_id FROM symbols WHERE id = p.symbol_id) AS parent_dso_id,'
544 '(SELECT dso FROM symbols_view WHERE id = p.symbol_id) AS parent_dso_short_name'
545 ' FROM call_paths c INNER JOIN call_paths p ON p.id = c.parent_id')
546 if perf_db_export_calls:
547 do_query(query, 'CREATE VIEW calls_view AS '
551 '(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
552 '(SELECT tid FROM threads WHERE id = thread_id) AS tid,'
553 '(SELECT comm FROM comms WHERE id = comm_id) AS command,'
557 '(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
560 'return_time - call_time AS elapsed_time,'
564 'CASE WHEN cyc_count=0 THEN CAST(0 AS NUMERIC(20, 2)) ELSE CAST((CAST(insn_count AS FLOAT) / cyc_count) AS NUMERIC(20, 2)) END AS IPC,'
567 '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,'
568 'parent_call_path_id,'
570 ' FROM calls INNER JOIN call_paths ON call_paths.id = call_path_id')
572 do_query(query, 'CREATE VIEW samples_view AS '
577 '(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
578 '(SELECT tid FROM threads WHERE id = thread_id) AS tid,'
579 '(SELECT comm FROM comms WHERE id = comm_id) AS command,'
580 '(SELECT name FROM selected_events WHERE id = evsel_id) AS event,'
581 'to_hex(ip) AS ip_hex,'
582 '(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
584 '(SELECT short_name FROM dsos WHERE id = dso_id) AS dso_short_name,'
585 'to_hex(to_ip) AS to_ip_hex,'
586 '(SELECT name FROM symbols WHERE id = to_symbol_id) AS to_symbol,'
588 '(SELECT short_name FROM dsos WHERE id = to_dso_id) AS to_dso_short_name,'
589 '(SELECT name FROM branch_types WHERE id = branch_type) AS branch_type_name,'
593 'CASE WHEN cyc_count=0 THEN CAST(0 AS NUMERIC(20, 2)) ELSE CAST((CAST(insn_count AS FLOAT) / cyc_count) AS NUMERIC(20, 2)) END AS IPC'
596 do_query(query, 'CREATE VIEW ptwrite_view AS '
601 'to_hex(payload) AS payload_hex,'
602 'CASE WHEN exact_ip=FALSE THEN \'False\' ELSE \'True\' END AS exact_ip'
604 ' INNER JOIN samples ON samples.id = ptwrite.id')
606 do_query(query, 'CREATE VIEW cbr_view AS '
615 ' INNER JOIN samples ON samples.id = cbr.id')
617 do_query(query, 'CREATE VIEW mwait_view AS '
622 'to_hex(hints) AS hints_hex,'
623 'to_hex(extensions) AS extensions_hex'
625 ' INNER JOIN samples ON samples.id = mwait.id')
627 do_query(query, 'CREATE VIEW pwre_view AS '
634 'CASE WHEN hw=FALSE THEN \'False\' ELSE \'True\' END AS hw'
636 ' INNER JOIN samples ON samples.id = pwre.id')
638 do_query(query, 'CREATE VIEW exstop_view AS '
643 'CASE WHEN exact_ip=FALSE THEN \'False\' ELSE \'True\' END AS exact_ip'
645 ' INNER JOIN samples ON samples.id = exstop.id')
647 do_query(query, 'CREATE VIEW pwrx_view AS '
654 'CASE WHEN wake_reason=1 THEN \'Interrupt\''
655 ' WHEN wake_reason=2 THEN \'Timer Deadline\''
656 ' WHEN wake_reason=4 THEN \'Monitored Address\''
657 ' WHEN wake_reason=8 THEN \'HW\''
658 ' ELSE CAST ( wake_reason AS VARCHAR(2) )'
661 ' INNER JOIN samples ON samples.id = pwrx.id')
663 do_query(query, 'CREATE VIEW power_events_view AS '
668 'selected_events.name AS event,'
669 'FORMAT(\'%6s\', cbr.cbr) AS cbr,'
670 'FORMAT(\'%6s\', cbr.mhz) AS MHz,'
671 'FORMAT(\'%5s\', cbr.percent) AS percent,'
672 'to_hex(mwait.hints) AS hints_hex,'
673 'to_hex(mwait.extensions) AS extensions_hex,'
674 'FORMAT(\'%3s\', pwre.cstate) AS cstate,'
675 'FORMAT(\'%3s\', pwre.subcstate) AS subcstate,'
676 'CASE WHEN pwre.hw=FALSE THEN \'False\' WHEN pwre.hw=TRUE THEN \'True\' ELSE NULL END AS hw,'
677 'CASE WHEN exstop.exact_ip=FALSE THEN \'False\' WHEN exstop.exact_ip=TRUE THEN \'True\' ELSE NULL END AS exact_ip,'
678 'FORMAT(\'%3s\', pwrx.deepest_cstate) AS deepest_cstate,'
679 'FORMAT(\'%3s\', pwrx.last_cstate) AS last_cstate,'
680 'CASE WHEN pwrx.wake_reason=1 THEN \'Interrupt\''
681 ' WHEN pwrx.wake_reason=2 THEN \'Timer Deadline\''
682 ' WHEN pwrx.wake_reason=4 THEN \'Monitored Address\''
683 ' WHEN pwrx.wake_reason=8 THEN \'HW\''
684 ' ELSE FORMAT(\'%2s\', pwrx.wake_reason)'
687 ' FULL JOIN mwait ON mwait.id = cbr.id'
688 ' FULL JOIN pwre ON pwre.id = cbr.id'
689 ' FULL JOIN exstop ON exstop.id = cbr.id'
690 ' FULL JOIN pwrx ON pwrx.id = cbr.id'
691 ' INNER JOIN samples ON samples.id = coalesce(cbr.id, mwait.id, pwre.id, exstop.id, pwrx.id)'
692 ' INNER JOIN selected_events ON selected_events.id = samples.evsel_id'
693 ' ORDER BY samples.id')
695 file_header = struct.pack("!11sii", b"PGCOPY\n\377\r\n\0", 0, 0)
696 file_trailer = b"\377\377"
698 def open_output_file(file_name):
699 path_name = output_dir_name + "/" + file_name
700 file = open(path_name, "wb+")
701 file.write(file_header)
704 def close_output_file(file):
705 file.write(file_trailer)
708 def copy_output_file_direct(file, table_name):
709 close_output_file(file)
710 sql = "COPY " + table_name + " FROM '" + file.name + "' (FORMAT 'binary')"
713 # Use COPY FROM STDIN because security may prevent postgres from accessing the files directly
714 def copy_output_file(file, table_name):
715 conn = PQconnectdb(toclientstr("dbname = " + dbname))
717 raise Exception("COPY FROM STDIN PQconnectdb failed")
718 file.write(file_trailer)
720 sql = "COPY " + table_name + " FROM STDIN (FORMAT 'binary')"
721 res = PQexec(conn, toclientstr(sql))
722 if (PQresultStatus(res) != 4):
723 raise Exception("COPY FROM STDIN PQexec failed")
724 data = file.read(65536)
726 ret = PQputCopyData(conn, data, len(data))
728 raise Exception("COPY FROM STDIN PQputCopyData failed, error " + str(ret))
729 data = file.read(65536)
730 ret = PQputCopyEnd(conn, None)
732 raise Exception("COPY FROM STDIN PQputCopyEnd failed, error " + str(ret))
735 def remove_output_file(file):
740 evsel_file = open_output_file("evsel_table.bin")
741 machine_file = open_output_file("machine_table.bin")
742 thread_file = open_output_file("thread_table.bin")
743 comm_file = open_output_file("comm_table.bin")
744 comm_thread_file = open_output_file("comm_thread_table.bin")
745 dso_file = open_output_file("dso_table.bin")
746 symbol_file = open_output_file("symbol_table.bin")
747 branch_type_file = open_output_file("branch_type_table.bin")
748 sample_file = open_output_file("sample_table.bin")
749 if perf_db_export_calls or perf_db_export_callchains:
750 call_path_file = open_output_file("call_path_table.bin")
751 if perf_db_export_calls:
752 call_file = open_output_file("call_table.bin")
753 ptwrite_file = open_output_file("ptwrite_table.bin")
754 cbr_file = open_output_file("cbr_table.bin")
755 mwait_file = open_output_file("mwait_table.bin")
756 pwre_file = open_output_file("pwre_table.bin")
757 exstop_file = open_output_file("exstop_table.bin")
758 pwrx_file = open_output_file("pwrx_table.bin")
761 printdate("Writing to intermediate files...")
762 # id == 0 means unknown. It is easier to create records for them than replace the zeroes with NULLs
763 evsel_table(0, "unknown")
764 machine_table(0, 0, "unknown")
765 thread_table(0, 0, 0, -1, -1)
766 comm_table(0, "unknown")
767 dso_table(0, 0, "unknown", "unknown", "")
768 symbol_table(0, 0, 0, 0, 0, "unknown")
769 sample_table(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
770 if perf_db_export_calls or perf_db_export_callchains:
771 call_path_table(0, 0, 0, 0)
772 call_return_table(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
776 def is_table_empty(table_name):
777 do_query(query, 'SELECT * FROM ' + table_name + ' LIMIT 1');
782 def drop(table_name):
783 do_query(query, 'DROP VIEW ' + table_name + '_view');
784 do_query(query, 'DROP TABLE ' + table_name);
787 printdate("Copying to database...")
788 copy_output_file(evsel_file, "selected_events")
789 copy_output_file(machine_file, "machines")
790 copy_output_file(thread_file, "threads")
791 copy_output_file(comm_file, "comms")
792 copy_output_file(comm_thread_file, "comm_threads")
793 copy_output_file(dso_file, "dsos")
794 copy_output_file(symbol_file, "symbols")
795 copy_output_file(branch_type_file, "branch_types")
796 copy_output_file(sample_file, "samples")
797 if perf_db_export_calls or perf_db_export_callchains:
798 copy_output_file(call_path_file, "call_paths")
799 if perf_db_export_calls:
800 copy_output_file(call_file, "calls")
801 copy_output_file(ptwrite_file, "ptwrite")
802 copy_output_file(cbr_file, "cbr")
803 copy_output_file(mwait_file, "mwait")
804 copy_output_file(pwre_file, "pwre")
805 copy_output_file(exstop_file, "exstop")
806 copy_output_file(pwrx_file, "pwrx")
808 printdate("Removing intermediate files...")
809 remove_output_file(evsel_file)
810 remove_output_file(machine_file)
811 remove_output_file(thread_file)
812 remove_output_file(comm_file)
813 remove_output_file(comm_thread_file)
814 remove_output_file(dso_file)
815 remove_output_file(symbol_file)
816 remove_output_file(branch_type_file)
817 remove_output_file(sample_file)
818 if perf_db_export_calls or perf_db_export_callchains:
819 remove_output_file(call_path_file)
820 if perf_db_export_calls:
821 remove_output_file(call_file)
822 remove_output_file(ptwrite_file)
823 remove_output_file(cbr_file)
824 remove_output_file(mwait_file)
825 remove_output_file(pwre_file)
826 remove_output_file(exstop_file)
827 remove_output_file(pwrx_file)
828 os.rmdir(output_dir_name)
829 printdate("Adding primary keys")
830 do_query(query, 'ALTER TABLE selected_events ADD PRIMARY KEY (id)')
831 do_query(query, 'ALTER TABLE machines ADD PRIMARY KEY (id)')
832 do_query(query, 'ALTER TABLE threads ADD PRIMARY KEY (id)')
833 do_query(query, 'ALTER TABLE comms ADD PRIMARY KEY (id)')
834 do_query(query, 'ALTER TABLE comm_threads ADD PRIMARY KEY (id)')
835 do_query(query, 'ALTER TABLE dsos ADD PRIMARY KEY (id)')
836 do_query(query, 'ALTER TABLE symbols ADD PRIMARY KEY (id)')
837 do_query(query, 'ALTER TABLE branch_types ADD PRIMARY KEY (id)')
838 do_query(query, 'ALTER TABLE samples ADD PRIMARY KEY (id)')
839 if perf_db_export_calls or perf_db_export_callchains:
840 do_query(query, 'ALTER TABLE call_paths ADD PRIMARY KEY (id)')
841 if perf_db_export_calls:
842 do_query(query, 'ALTER TABLE calls ADD PRIMARY KEY (id)')
843 do_query(query, 'ALTER TABLE ptwrite ADD PRIMARY KEY (id)')
844 do_query(query, 'ALTER TABLE cbr ADD PRIMARY KEY (id)')
845 do_query(query, 'ALTER TABLE mwait ADD PRIMARY KEY (id)')
846 do_query(query, 'ALTER TABLE pwre ADD PRIMARY KEY (id)')
847 do_query(query, 'ALTER TABLE exstop ADD PRIMARY KEY (id)')
848 do_query(query, 'ALTER TABLE pwrx ADD PRIMARY KEY (id)')
850 printdate("Adding foreign keys")
851 do_query(query, 'ALTER TABLE threads '
852 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),'
853 'ADD CONSTRAINT processfk FOREIGN KEY (process_id) REFERENCES threads (id)')
854 do_query(query, 'ALTER TABLE comm_threads '
855 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
856 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id)')
857 do_query(query, 'ALTER TABLE dsos '
858 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id)')
859 do_query(query, 'ALTER TABLE symbols '
860 'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id)')
861 do_query(query, 'ALTER TABLE samples '
862 'ADD CONSTRAINT evselfk FOREIGN KEY (evsel_id) REFERENCES selected_events (id),'
863 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),'
864 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),'
865 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
866 'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id),'
867 'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id),'
868 'ADD CONSTRAINT todsofk FOREIGN KEY (to_dso_id) REFERENCES dsos (id),'
869 'ADD CONSTRAINT tosymbolfk FOREIGN KEY (to_symbol_id) REFERENCES symbols (id)')
870 if perf_db_export_calls or perf_db_export_callchains:
871 do_query(query, 'ALTER TABLE call_paths '
872 'ADD CONSTRAINT parentfk FOREIGN KEY (parent_id) REFERENCES call_paths (id),'
873 'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id)')
874 if perf_db_export_calls:
875 do_query(query, 'ALTER TABLE calls '
876 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),'
877 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
878 'ADD CONSTRAINT call_pathfk FOREIGN KEY (call_path_id) REFERENCES call_paths (id),'
879 'ADD CONSTRAINT callfk FOREIGN KEY (call_id) REFERENCES samples (id),'
880 'ADD CONSTRAINT returnfk FOREIGN KEY (return_id) REFERENCES samples (id),'
881 'ADD CONSTRAINT parent_call_pathfk FOREIGN KEY (parent_call_path_id) REFERENCES call_paths (id)')
882 do_query(query, 'CREATE INDEX pcpid_idx ON calls (parent_call_path_id)')
883 do_query(query, 'CREATE INDEX pid_idx ON calls (parent_id)')
884 do_query(query, 'ALTER TABLE ptwrite '
885 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
886 do_query(query, 'ALTER TABLE cbr '
887 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
888 do_query(query, 'ALTER TABLE mwait '
889 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
890 do_query(query, 'ALTER TABLE pwre '
891 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
892 do_query(query, 'ALTER TABLE exstop '
893 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
894 do_query(query, 'ALTER TABLE pwrx '
895 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
897 printdate("Dropping unused tables")
898 if is_table_empty("ptwrite"):
900 if is_table_empty("mwait") and is_table_empty("pwre") and is_table_empty("exstop") and is_table_empty("pwrx"):
901 do_query(query, 'DROP VIEW power_events_view');
906 if is_table_empty("cbr"):
909 if (unhandled_count):
910 printdate("Warning: ", unhandled_count, " unhandled events")
913 def trace_unhandled(event_name, context, event_fields_dict):
914 global unhandled_count
917 def sched__sched_switch(*x):
920 def evsel_table(evsel_id, evsel_name, *x):
921 evsel_name = toserverstr(evsel_name)
923 fmt = "!hiqi" + str(n) + "s"
924 value = struct.pack(fmt, 2, 8, evsel_id, n, evsel_name)
925 evsel_file.write(value)
927 def machine_table(machine_id, pid, root_dir, *x):
928 root_dir = toserverstr(root_dir)
930 fmt = "!hiqiii" + str(n) + "s"
931 value = struct.pack(fmt, 3, 8, machine_id, 4, pid, n, root_dir)
932 machine_file.write(value)
934 def thread_table(thread_id, machine_id, process_id, pid, tid, *x):
935 value = struct.pack("!hiqiqiqiiii", 5, 8, thread_id, 8, machine_id, 8, process_id, 4, pid, 4, tid)
936 thread_file.write(value)
938 def comm_table(comm_id, comm_str, *x):
939 comm_str = toserverstr(comm_str)
941 fmt = "!hiqi" + str(n) + "s"
942 value = struct.pack(fmt, 2, 8, comm_id, n, comm_str)
943 comm_file.write(value)
945 def comm_thread_table(comm_thread_id, comm_id, thread_id, *x):
947 value = struct.pack(fmt, 3, 8, comm_thread_id, 8, comm_id, 8, thread_id)
948 comm_thread_file.write(value)
950 def dso_table(dso_id, machine_id, short_name, long_name, build_id, *x):
951 short_name = toserverstr(short_name)
952 long_name = toserverstr(long_name)
953 build_id = toserverstr(build_id)
957 fmt = "!hiqiqi" + str(n1) + "si" + str(n2) + "si" + str(n3) + "s"
958 value = struct.pack(fmt, 5, 8, dso_id, 8, machine_id, n1, short_name, n2, long_name, n3, build_id)
959 dso_file.write(value)
961 def symbol_table(symbol_id, dso_id, sym_start, sym_end, binding, symbol_name, *x):
962 symbol_name = toserverstr(symbol_name)
964 fmt = "!hiqiqiqiqiii" + str(n) + "s"
965 value = struct.pack(fmt, 6, 8, symbol_id, 8, dso_id, 8, sym_start, 8, sym_end, 4, binding, n, symbol_name)
966 symbol_file.write(value)
968 def branch_type_table(branch_type, name, *x):
969 name = toserverstr(name)
971 fmt = "!hiii" + str(n) + "s"
972 value = struct.pack(fmt, 2, 4, branch_type, n, name)
973 branch_type_file.write(value)
975 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, call_path_id, insn_cnt, cyc_cnt, *x):
977 value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiiiBiqiqiq", 20, 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, 8, insn_cnt, 8, cyc_cnt)
979 value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiqiqiqiqiiiBiqiqiq", 24, 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, 8, insn_cnt, 8, cyc_cnt)
980 sample_file.write(value)
982 def call_path_table(cp_id, parent_id, symbol_id, ip, *x):
984 value = struct.pack(fmt, 4, 8, cp_id, 8, parent_id, 8, symbol_id, 8, ip)
985 call_path_file.write(value)
987 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, parent_id, insn_cnt, cyc_cnt, *x):
988 fmt = "!hiqiqiqiqiqiqiqiqiqiqiiiqiqiq"
989 value = struct.pack(fmt, 14, 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, 8, insn_cnt, 8, cyc_cnt)
990 call_file.write(value)
992 def ptwrite(id, raw_buf):
993 data = struct.unpack_from("<IQ", raw_buf)
997 value = struct.pack("!hiqiqiB", 3, 8, id, 8, payload, 1, exact_ip)
998 ptwrite_file.write(value)
1000 def cbr(id, raw_buf):
1001 data = struct.unpack_from("<BBBBII", raw_buf)
1003 MHz = (data[4] + 500) / 1000
1004 percent = ((cbr * 1000 / data[2]) + 5) / 10
1005 value = struct.pack("!hiqiiiiii", 4, 8, id, 4, cbr, 4, MHz, 4, percent)
1006 cbr_file.write(value)
1008 def mwait(id, raw_buf):
1009 data = struct.unpack_from("<IQ", raw_buf)
1011 hints = payload & 0xff
1012 extensions = (payload >> 32) & 0x3
1013 value = struct.pack("!hiqiiii", 3, 8, id, 4, hints, 4, extensions)
1014 mwait_file.write(value)
1016 def pwre(id, raw_buf):
1017 data = struct.unpack_from("<IQ", raw_buf)
1019 hw = (payload >> 7) & 1
1020 cstate = (payload >> 12) & 0xf
1021 subcstate = (payload >> 8) & 0xf
1022 value = struct.pack("!hiqiiiiiB", 4, 8, id, 4, cstate, 4, subcstate, 1, hw)
1023 pwre_file.write(value)
1025 def exstop(id, raw_buf):
1026 data = struct.unpack_from("<I", raw_buf)
1028 exact_ip = flags & 1
1029 value = struct.pack("!hiqiB", 2, 8, id, 1, exact_ip)
1030 exstop_file.write(value)
1032 def pwrx(id, raw_buf):
1033 data = struct.unpack_from("<IQ", raw_buf)
1035 deepest_cstate = payload & 0xf
1036 last_cstate = (payload >> 4) & 0xf
1037 wake_reason = (payload >> 8) & 0xf
1038 value = struct.pack("!hiqiiiiii", 4, 8, id, 4, deepest_cstate, 4, last_cstate, 4, wake_reason)
1039 pwrx_file.write(value)
1041 def synth_data(id, config, raw_buf, *x):
1043 ptwrite(id, raw_buf)