export-to-postgresql.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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. from __future__ import print_function
  13. import os
  14. import sys
  15. import struct
  16. import datetime
  17. # To use this script you will need to have installed package python-pyside which
  18. # provides LGPL-licensed Python bindings for Qt. You will also need the package
  19. # libqt4-sql-psql for Qt postgresql support.
  20. #
  21. # The script assumes postgresql is running on the local machine and that the
  22. # user has postgresql permissions to create databases. Examples of installing
  23. # postgresql and adding such a user are:
  24. #
  25. # fedora:
  26. #
  27. # $ sudo yum install postgresql postgresql-server qt-postgresql
  28. # $ sudo su - postgres -c initdb
  29. # $ sudo service postgresql start
  30. # $ sudo su - postgres
  31. # $ createuser -s <your user id here> # Older versions may not support -s, in which case answer the prompt below:
  32. # Shall the new role be a superuser? (y/n) y
  33. # $ sudo yum install python-pyside
  34. #
  35. # Alternately, to use Python3 and/or pyside 2, one of the following:
  36. # $ sudo yum install python3-pyside
  37. # $ pip install --user PySide2
  38. # $ pip3 install --user PySide2
  39. #
  40. # ubuntu:
  41. #
  42. # $ sudo apt-get install postgresql
  43. # $ sudo su - postgres
  44. # $ createuser -s <your user id here>
  45. # $ sudo apt-get install python-pyside.qtsql libqt4-sql-psql
  46. #
  47. # Alternately, to use Python3 and/or pyside 2, one of the following:
  48. #
  49. # $ sudo apt-get install python3-pyside.qtsql libqt4-sql-psql
  50. # $ sudo apt-get install python-pyside2.qtsql libqt5sql5-psql
  51. # $ sudo apt-get install python3-pyside2.qtsql libqt5sql5-psql
  52. #
  53. # An example of using this script with Intel PT:
  54. #
  55. # $ perf record -e intel_pt//u ls
  56. # $ perf script -s ~/libexec/perf-core/scripts/python/export-to-postgresql.py pt_example branches calls
  57. # 2015-05-29 12:49:23.464364 Creating database...
  58. # 2015-05-29 12:49:26.281717 Writing to intermediate files...
  59. # 2015-05-29 12:49:27.190383 Copying to database...
  60. # 2015-05-29 12:49:28.140451 Removing intermediate files...
  61. # 2015-05-29 12:49:28.147451 Adding primary keys
  62. # 2015-05-29 12:49:28.655683 Adding foreign keys
  63. # 2015-05-29 12:49:29.365350 Done
  64. #
  65. # To browse the database, psql can be used e.g.
  66. #
  67. # $ psql pt_example
  68. # pt_example=# select * from samples_view where id < 100;
  69. # pt_example=# \d+
  70. # pt_example=# \d+ samples_view
  71. # pt_example=# \q
  72. #
  73. # An example of using the database is provided by the script
  74. # exported-sql-viewer.py. Refer to that script for details.
  75. #
  76. # Tables:
  77. #
  78. # The tables largely correspond to perf tools' data structures. They are largely self-explanatory.
  79. #
  80. # samples
  81. #
  82. # 'samples' is the main table. It represents what instruction was executing at a point in time
  83. # when something (a selected event) happened. The memory address is the instruction pointer or 'ip'.
  84. #
  85. # calls
  86. #
  87. # 'calls' represents function calls and is related to 'samples' by 'call_id' and 'return_id'.
  88. # 'calls' is only created when the 'calls' option to this script is specified.
  89. #
  90. # call_paths
  91. #
  92. # 'call_paths' represents all the call stacks. Each 'call' has an associated record in 'call_paths'.
  93. # 'calls_paths' is only created when the 'calls' option to this script is specified.
  94. #
  95. # branch_types
  96. #
  97. # 'branch_types' provides descriptions for each type of branch.
  98. #
  99. # comm_threads
  100. #
  101. # 'comm_threads' shows how 'comms' relates to 'threads'.
  102. #
  103. # comms
  104. #
  105. # 'comms' contains a record for each 'comm' - the name given to the executable that is running.
  106. #
  107. # dsos
  108. #
  109. # 'dsos' contains a record for each executable file or library.
  110. #
  111. # machines
  112. #
  113. # 'machines' can be used to distinguish virtual machines if virtualization is supported.
  114. #
  115. # selected_events
  116. #
  117. # 'selected_events' contains a record for each kind of event that has been sampled.
  118. #
  119. # symbols
  120. #
  121. # 'symbols' contains a record for each symbol. Only symbols that have samples are present.
  122. #
  123. # threads
  124. #
  125. # 'threads' contains a record for each thread.
  126. #
  127. # Views:
  128. #
  129. # Most of the tables have views for more friendly display. The views are:
  130. #
  131. # calls_view
  132. # call_paths_view
  133. # comm_threads_view
  134. # dsos_view
  135. # machines_view
  136. # samples_view
  137. # symbols_view
  138. # threads_view
  139. #
  140. # More examples of browsing the database with psql:
  141. # Note that some of the examples are not the most optimal SQL query.
  142. # Note that call information is only available if the script's 'calls' option has been used.
  143. #
  144. # Top 10 function calls (not aggregated by symbol):
  145. #
  146. # SELECT * FROM calls_view ORDER BY elapsed_time DESC LIMIT 10;
  147. #
  148. # Top 10 function calls (aggregated by symbol):
  149. #
  150. # SELECT symbol_id,(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,
  151. # SUM(elapsed_time) AS tot_elapsed_time,SUM(branch_count) AS tot_branch_count
  152. # FROM calls_view GROUP BY symbol_id ORDER BY tot_elapsed_time DESC LIMIT 10;
  153. #
  154. # Note that the branch count gives a rough estimation of cpu usage, so functions
  155. # that took a long time but have a relatively low branch count must have spent time
  156. # waiting.
  157. #
  158. # Find symbols by pattern matching on part of the name (e.g. names containing 'alloc'):
  159. #
  160. # SELECT * FROM symbols_view WHERE name LIKE '%alloc%';
  161. #
  162. # Top 10 function calls for a specific symbol (e.g. whose symbol_id is 187):
  163. #
  164. # SELECT * FROM calls_view WHERE symbol_id = 187 ORDER BY elapsed_time DESC LIMIT 10;
  165. #
  166. # Show function calls made by function in the same context (i.e. same call path) (e.g. one with call_path_id 254):
  167. #
  168. # SELECT * FROM calls_view WHERE parent_call_path_id = 254;
  169. #
  170. # Show branches made during a function call (e.g. where call_id is 29357 and return_id is 29370 and tid is 29670)
  171. #
  172. # SELECT * FROM samples_view WHERE id >= 29357 AND id <= 29370 AND tid = 29670 AND event LIKE 'branches%';
  173. #
  174. # Show transactions:
  175. #
  176. # SELECT * FROM samples_view WHERE event = 'transactions';
  177. #
  178. # Note transaction start has 'in_tx' true whereas, transaction end has 'in_tx' false.
  179. # Transaction aborts have branch_type_name 'transaction abort'
  180. #
  181. # Show transaction aborts:
  182. #
  183. # SELECT * FROM samples_view WHERE event = 'transactions' AND branch_type_name = 'transaction abort';
  184. #
  185. # To print a call stack requires walking the call_paths table. For example this python script:
  186. # #!/usr/bin/python2
  187. #
  188. # import sys
  189. # from PySide.QtSql import *
  190. #
  191. # if __name__ == '__main__':
  192. # if (len(sys.argv) < 3):
  193. # print >> sys.stderr, "Usage is: printcallstack.py <database name> <call_path_id>"
  194. # raise Exception("Too few arguments")
  195. # dbname = sys.argv[1]
  196. # call_path_id = sys.argv[2]
  197. # db = QSqlDatabase.addDatabase('QPSQL')
  198. # db.setDatabaseName(dbname)
  199. # if not db.open():
  200. # raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text())
  201. # query = QSqlQuery(db)
  202. # print " id ip symbol_id symbol dso_id dso_short_name"
  203. # while call_path_id != 0 and call_path_id != 1:
  204. # ret = query.exec_('SELECT * FROM call_paths_view WHERE id = ' + str(call_path_id))
  205. # if not ret:
  206. # raise Exception("Query failed: " + query.lastError().text())
  207. # if not query.next():
  208. # raise Exception("Query failed")
  209. # 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))
  210. # call_path_id = query.value(6)
  211. pyside_version_1 = True
  212. if not "pyside-version-1" in sys.argv:
  213. try:
  214. from PySide2.QtSql import *
  215. pyside_version_1 = False
  216. except:
  217. pass
  218. if pyside_version_1:
  219. from PySide.QtSql import *
  220. if sys.version_info < (3, 0):
  221. def toserverstr(str):
  222. return str
  223. def toclientstr(str):
  224. return str
  225. else:
  226. # Assume UTF-8 server_encoding and client_encoding
  227. def toserverstr(str):
  228. return bytes(str, "UTF_8")
  229. def toclientstr(str):
  230. return bytes(str, "UTF_8")
  231. # Need to access PostgreSQL C library directly to use COPY FROM STDIN
  232. from ctypes import *
  233. libpq = CDLL("libpq.so.5")
  234. PQconnectdb = libpq.PQconnectdb
  235. PQconnectdb.restype = c_void_p
  236. PQconnectdb.argtypes = [ c_char_p ]
  237. PQfinish = libpq.PQfinish
  238. PQfinish.argtypes = [ c_void_p ]
  239. PQstatus = libpq.PQstatus
  240. PQstatus.restype = c_int
  241. PQstatus.argtypes = [ c_void_p ]
  242. PQexec = libpq.PQexec
  243. PQexec.restype = c_void_p
  244. PQexec.argtypes = [ c_void_p, c_char_p ]
  245. PQresultStatus = libpq.PQresultStatus
  246. PQresultStatus.restype = c_int
  247. PQresultStatus.argtypes = [ c_void_p ]
  248. PQputCopyData = libpq.PQputCopyData
  249. PQputCopyData.restype = c_int
  250. PQputCopyData.argtypes = [ c_void_p, c_void_p, c_int ]
  251. PQputCopyEnd = libpq.PQputCopyEnd
  252. PQputCopyEnd.restype = c_int
  253. PQputCopyEnd.argtypes = [ c_void_p, c_void_p ]
  254. sys.path.append(os.environ['PERF_EXEC_PATH'] + \
  255. '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
  256. # These perf imports are not used at present
  257. #from perf_trace_context import *
  258. #from Core import *
  259. perf_db_export_mode = True
  260. perf_db_export_calls = False
  261. perf_db_export_callchains = False
  262. def printerr(*args, **kw_args):
  263. print(*args, file=sys.stderr, **kw_args)
  264. def printdate(*args, **kw_args):
  265. print(datetime.datetime.today(), *args, sep=' ', **kw_args)
  266. def usage():
  267. printerr("Usage is: export-to-postgresql.py <database name> [<columns>] [<calls>] [<callchains>] [<pyside-version-1>]");
  268. printerr("where: columns 'all' or 'branches'");
  269. printerr(" calls 'calls' => create calls and call_paths table");
  270. printerr(" callchains 'callchains' => create call_paths table");
  271. printerr(" pyside-version-1 'pyside-version-1' => use pyside version 1");
  272. raise Exception("Too few or bad arguments")
  273. if (len(sys.argv) < 2):
  274. usage()
  275. dbname = sys.argv[1]
  276. if (len(sys.argv) >= 3):
  277. columns = sys.argv[2]
  278. else:
  279. columns = "all"
  280. if columns not in ("all", "branches"):
  281. usage()
  282. branches = (columns == "branches")
  283. for i in range(3,len(sys.argv)):
  284. if (sys.argv[i] == "calls"):
  285. perf_db_export_calls = True
  286. elif (sys.argv[i] == "callchains"):
  287. perf_db_export_callchains = True
  288. elif (sys.argv[i] == "pyside-version-1"):
  289. pass
  290. else:
  291. usage()
  292. output_dir_name = os.getcwd() + "/" + dbname + "-perf-data"
  293. os.mkdir(output_dir_name)
  294. def do_query(q, s):
  295. if (q.exec_(s)):
  296. return
  297. raise Exception("Query failed: " + q.lastError().text())
  298. printdate("Creating database...")
  299. db = QSqlDatabase.addDatabase('QPSQL')
  300. query = QSqlQuery(db)
  301. db.setDatabaseName('postgres')
  302. db.open()
  303. try:
  304. do_query(query, 'CREATE DATABASE ' + dbname)
  305. except:
  306. os.rmdir(output_dir_name)
  307. raise
  308. query.finish()
  309. query.clear()
  310. db.close()
  311. db.setDatabaseName(dbname)
  312. db.open()
  313. query = QSqlQuery(db)
  314. do_query(query, 'SET client_min_messages TO WARNING')
  315. do_query(query, 'CREATE TABLE selected_events ('
  316. 'id bigint NOT NULL,'
  317. 'name varchar(80))')
  318. do_query(query, 'CREATE TABLE machines ('
  319. 'id bigint NOT NULL,'
  320. 'pid integer,'
  321. 'root_dir varchar(4096))')
  322. do_query(query, 'CREATE TABLE threads ('
  323. 'id bigint NOT NULL,'
  324. 'machine_id bigint,'
  325. 'process_id bigint,'
  326. 'pid integer,'
  327. 'tid integer)')
  328. do_query(query, 'CREATE TABLE comms ('
  329. 'id bigint NOT NULL,'
  330. 'comm varchar(16),'
  331. 'c_thread_id bigint,'
  332. 'c_time bigint,'
  333. 'exec_flag boolean)')
  334. do_query(query, 'CREATE TABLE comm_threads ('
  335. 'id bigint NOT NULL,'
  336. 'comm_id bigint,'
  337. 'thread_id bigint)')
  338. do_query(query, 'CREATE TABLE dsos ('
  339. 'id bigint NOT NULL,'
  340. 'machine_id bigint,'
  341. 'short_name varchar(256),'
  342. 'long_name varchar(4096),'
  343. 'build_id varchar(64))')
  344. do_query(query, 'CREATE TABLE symbols ('
  345. 'id bigint NOT NULL,'
  346. 'dso_id bigint,'
  347. 'sym_start bigint,'
  348. 'sym_end bigint,'
  349. 'binding integer,'
  350. 'name varchar(2048))')
  351. do_query(query, 'CREATE TABLE branch_types ('
  352. 'id integer NOT NULL,'
  353. 'name varchar(80))')
  354. if branches:
  355. do_query(query, 'CREATE TABLE samples ('
  356. 'id bigint NOT NULL,'
  357. 'evsel_id bigint,'
  358. 'machine_id bigint,'
  359. 'thread_id bigint,'
  360. 'comm_id bigint,'
  361. 'dso_id bigint,'
  362. 'symbol_id bigint,'
  363. 'sym_offset bigint,'
  364. 'ip bigint,'
  365. 'time bigint,'
  366. 'cpu integer,'
  367. 'to_dso_id bigint,'
  368. 'to_symbol_id bigint,'
  369. 'to_sym_offset bigint,'
  370. 'to_ip bigint,'
  371. 'branch_type integer,'
  372. 'in_tx boolean,'
  373. 'call_path_id bigint,'
  374. 'insn_count bigint,'
  375. 'cyc_count bigint,'
  376. 'flags integer)')
  377. else:
  378. do_query(query, 'CREATE TABLE samples ('
  379. 'id bigint NOT NULL,'
  380. 'evsel_id bigint,'
  381. 'machine_id bigint,'
  382. 'thread_id bigint,'
  383. 'comm_id bigint,'
  384. 'dso_id bigint,'
  385. 'symbol_id bigint,'
  386. 'sym_offset bigint,'
  387. 'ip bigint,'
  388. 'time bigint,'
  389. 'cpu integer,'
  390. 'to_dso_id bigint,'
  391. 'to_symbol_id bigint,'
  392. 'to_sym_offset bigint,'
  393. 'to_ip bigint,'
  394. 'period bigint,'
  395. 'weight bigint,'
  396. 'transaction bigint,'
  397. 'data_src bigint,'
  398. 'branch_type integer,'
  399. 'in_tx boolean,'
  400. 'call_path_id bigint,'
  401. 'insn_count bigint,'
  402. 'cyc_count bigint,'
  403. 'flags integer)')
  404. if perf_db_export_calls or perf_db_export_callchains:
  405. do_query(query, 'CREATE TABLE call_paths ('
  406. 'id bigint NOT NULL,'
  407. 'parent_id bigint,'
  408. 'symbol_id bigint,'
  409. 'ip bigint)')
  410. if perf_db_export_calls:
  411. do_query(query, 'CREATE TABLE calls ('
  412. 'id bigint NOT NULL,'
  413. 'thread_id bigint,'
  414. 'comm_id bigint,'
  415. 'call_path_id bigint,'
  416. 'call_time bigint,'
  417. 'return_time bigint,'
  418. 'branch_count bigint,'
  419. 'call_id bigint,'
  420. 'return_id bigint,'
  421. 'parent_call_path_id bigint,'
  422. 'flags integer,'
  423. 'parent_id bigint,'
  424. 'insn_count bigint,'
  425. 'cyc_count bigint)')
  426. do_query(query, 'CREATE TABLE ptwrite ('
  427. 'id bigint NOT NULL,'
  428. 'payload bigint,'
  429. 'exact_ip boolean)')
  430. do_query(query, 'CREATE TABLE cbr ('
  431. 'id bigint NOT NULL,'
  432. 'cbr integer,'
  433. 'mhz integer,'
  434. 'percent integer)')
  435. do_query(query, 'CREATE TABLE mwait ('
  436. 'id bigint NOT NULL,'
  437. 'hints integer,'
  438. 'extensions integer)')
  439. do_query(query, 'CREATE TABLE pwre ('
  440. 'id bigint NOT NULL,'
  441. 'cstate integer,'
  442. 'subcstate integer,'
  443. 'hw boolean)')
  444. do_query(query, 'CREATE TABLE exstop ('
  445. 'id bigint NOT NULL,'
  446. 'exact_ip boolean)')
  447. do_query(query, 'CREATE TABLE pwrx ('
  448. 'id bigint NOT NULL,'
  449. 'deepest_cstate integer,'
  450. 'last_cstate integer,'
  451. 'wake_reason integer)')
  452. do_query(query, 'CREATE TABLE context_switches ('
  453. 'id bigint NOT NULL,'
  454. 'machine_id bigint,'
  455. 'time bigint,'
  456. 'cpu integer,'
  457. 'thread_out_id bigint,'
  458. 'comm_out_id bigint,'
  459. 'thread_in_id bigint,'
  460. 'comm_in_id bigint,'
  461. 'flags integer)')
  462. do_query(query, 'CREATE VIEW machines_view AS '
  463. 'SELECT '
  464. 'id,'
  465. 'pid,'
  466. 'root_dir,'
  467. 'CASE WHEN id=0 THEN \'unknown\' WHEN pid=-1 THEN \'host\' ELSE \'guest\' END AS host_or_guest'
  468. ' FROM machines')
  469. do_query(query, 'CREATE VIEW dsos_view AS '
  470. 'SELECT '
  471. 'id,'
  472. 'machine_id,'
  473. '(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
  474. 'short_name,'
  475. 'long_name,'
  476. 'build_id'
  477. ' FROM dsos')
  478. do_query(query, 'CREATE VIEW symbols_view AS '
  479. 'SELECT '
  480. 'id,'
  481. 'name,'
  482. '(SELECT short_name FROM dsos WHERE id=dso_id) AS dso,'
  483. 'dso_id,'
  484. 'sym_start,'
  485. 'sym_end,'
  486. 'CASE WHEN binding=0 THEN \'local\' WHEN binding=1 THEN \'global\' ELSE \'weak\' END AS binding'
  487. ' FROM symbols')
  488. do_query(query, 'CREATE VIEW threads_view AS '
  489. 'SELECT '
  490. 'id,'
  491. 'machine_id,'
  492. '(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,'
  493. 'process_id,'
  494. 'pid,'
  495. 'tid'
  496. ' FROM threads')
  497. do_query(query, 'CREATE VIEW comm_threads_view AS '
  498. 'SELECT '
  499. 'comm_id,'
  500. '(SELECT comm FROM comms WHERE id = comm_id) AS command,'
  501. 'thread_id,'
  502. '(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
  503. '(SELECT tid FROM threads WHERE id = thread_id) AS tid'
  504. ' FROM comm_threads')
  505. if perf_db_export_calls or perf_db_export_callchains:
  506. do_query(query, 'CREATE VIEW call_paths_view AS '
  507. 'SELECT '
  508. 'c.id,'
  509. 'to_hex(c.ip) AS ip,'
  510. 'c.symbol_id,'
  511. '(SELECT name FROM symbols WHERE id = c.symbol_id) AS symbol,'
  512. '(SELECT dso_id FROM symbols WHERE id = c.symbol_id) AS dso_id,'
  513. '(SELECT dso FROM symbols_view WHERE id = c.symbol_id) AS dso_short_name,'
  514. 'c.parent_id,'
  515. 'to_hex(p.ip) AS parent_ip,'
  516. 'p.symbol_id AS parent_symbol_id,'
  517. '(SELECT name FROM symbols WHERE id = p.symbol_id) AS parent_symbol,'
  518. '(SELECT dso_id FROM symbols WHERE id = p.symbol_id) AS parent_dso_id,'
  519. '(SELECT dso FROM symbols_view WHERE id = p.symbol_id) AS parent_dso_short_name'
  520. ' FROM call_paths c INNER JOIN call_paths p ON p.id = c.parent_id')
  521. if perf_db_export_calls:
  522. do_query(query, 'CREATE VIEW calls_view AS '
  523. 'SELECT '
  524. 'calls.id,'
  525. 'thread_id,'
  526. '(SELECT pid FROM threads WHERE id = thread_id) AS pid,'
  527. '(SELECT tid FROM threads WHERE id = thread_id) AS tid,'
  528. '(SELECT comm FROM comms WHERE id = comm_id) AS command,'
  529. 'call_path_id,'
  530. 'to_hex(ip) AS ip,'
  531. 'symbol_id,'
  532. '(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
  533. 'call_time,'
  534. 'return_time,'
  535. 'return_time - call_time AS elapsed_time,'
  536. 'branch_count,'
  537. 'insn_count,'
  538. 'cyc_count,'
  539. '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,'
  540. 'call_id,'
  541. 'return_id,'
  542. '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,'
  543. 'parent_call_path_id,'
  544. 'calls.parent_id'
  545. ' FROM calls INNER JOIN call_paths ON call_paths.id = call_path_id')
  546. do_query(query, 'CREATE VIEW samples_view AS '
  547. 'SELECT '
  548. 'id,'
  549. 'time,'
  550. 'cpu,'
  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,'
  554. '(SELECT name FROM selected_events WHERE id = evsel_id) AS event,'
  555. 'to_hex(ip) AS ip_hex,'
  556. '(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,'
  557. 'sym_offset,'
  558. '(SELECT short_name FROM dsos WHERE id = dso_id) AS dso_short_name,'
  559. 'to_hex(to_ip) AS to_ip_hex,'
  560. '(SELECT name FROM symbols WHERE id = to_symbol_id) AS to_symbol,'
  561. 'to_sym_offset,'
  562. '(SELECT short_name FROM dsos WHERE id = to_dso_id) AS to_dso_short_name,'
  563. '(SELECT name FROM branch_types WHERE id = branch_type) AS branch_type_name,'
  564. 'in_tx,'
  565. 'insn_count,'
  566. 'cyc_count,'
  567. '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,'
  568. 'flags'
  569. ' FROM samples')
  570. do_query(query, 'CREATE VIEW ptwrite_view AS '
  571. 'SELECT '
  572. 'ptwrite.id,'
  573. 'time,'
  574. 'cpu,'
  575. 'to_hex(payload) AS payload_hex,'
  576. 'CASE WHEN exact_ip=FALSE THEN \'False\' ELSE \'True\' END AS exact_ip'
  577. ' FROM ptwrite'
  578. ' INNER JOIN samples ON samples.id = ptwrite.id')
  579. do_query(query, 'CREATE VIEW cbr_view AS '
  580. 'SELECT '
  581. 'cbr.id,'
  582. 'time,'
  583. 'cpu,'
  584. 'cbr,'
  585. 'mhz,'
  586. 'percent'
  587. ' FROM cbr'
  588. ' INNER JOIN samples ON samples.id = cbr.id')
  589. do_query(query, 'CREATE VIEW mwait_view AS '
  590. 'SELECT '
  591. 'mwait.id,'
  592. 'time,'
  593. 'cpu,'
  594. 'to_hex(hints) AS hints_hex,'
  595. 'to_hex(extensions) AS extensions_hex'
  596. ' FROM mwait'
  597. ' INNER JOIN samples ON samples.id = mwait.id')
  598. do_query(query, 'CREATE VIEW pwre_view AS '
  599. 'SELECT '
  600. 'pwre.id,'
  601. 'time,'
  602. 'cpu,'
  603. 'cstate,'
  604. 'subcstate,'
  605. 'CASE WHEN hw=FALSE THEN \'False\' ELSE \'True\' END AS hw'
  606. ' FROM pwre'
  607. ' INNER JOIN samples ON samples.id = pwre.id')
  608. do_query(query, 'CREATE VIEW exstop_view AS '
  609. 'SELECT '
  610. 'exstop.id,'
  611. 'time,'
  612. 'cpu,'
  613. 'CASE WHEN exact_ip=FALSE THEN \'False\' ELSE \'True\' END AS exact_ip'
  614. ' FROM exstop'
  615. ' INNER JOIN samples ON samples.id = exstop.id')
  616. do_query(query, 'CREATE VIEW pwrx_view AS '
  617. 'SELECT '
  618. 'pwrx.id,'
  619. 'time,'
  620. 'cpu,'
  621. 'deepest_cstate,'
  622. 'last_cstate,'
  623. 'CASE WHEN wake_reason=1 THEN \'Interrupt\''
  624. ' WHEN wake_reason=2 THEN \'Timer Deadline\''
  625. ' WHEN wake_reason=4 THEN \'Monitored Address\''
  626. ' WHEN wake_reason=8 THEN \'HW\''
  627. ' ELSE CAST ( wake_reason AS VARCHAR(2) )'
  628. 'END AS wake_reason'
  629. ' FROM pwrx'
  630. ' INNER JOIN samples ON samples.id = pwrx.id')
  631. do_query(query, 'CREATE VIEW power_events_view AS '
  632. 'SELECT '
  633. 'samples.id,'
  634. 'samples.time,'
  635. 'samples.cpu,'
  636. 'selected_events.name AS event,'
  637. 'FORMAT(\'%6s\', cbr.cbr) AS cbr,'
  638. 'FORMAT(\'%6s\', cbr.mhz) AS MHz,'
  639. 'FORMAT(\'%5s\', cbr.percent) AS percent,'
  640. 'to_hex(mwait.hints) AS hints_hex,'
  641. 'to_hex(mwait.extensions) AS extensions_hex,'
  642. 'FORMAT(\'%3s\', pwre.cstate) AS cstate,'
  643. 'FORMAT(\'%3s\', pwre.subcstate) AS subcstate,'
  644. 'CASE WHEN pwre.hw=FALSE THEN \'False\' WHEN pwre.hw=TRUE THEN \'True\' ELSE NULL END AS hw,'
  645. 'CASE WHEN exstop.exact_ip=FALSE THEN \'False\' WHEN exstop.exact_ip=TRUE THEN \'True\' ELSE NULL END AS exact_ip,'
  646. 'FORMAT(\'%3s\', pwrx.deepest_cstate) AS deepest_cstate,'
  647. 'FORMAT(\'%3s\', pwrx.last_cstate) AS last_cstate,'
  648. 'CASE WHEN pwrx.wake_reason=1 THEN \'Interrupt\''
  649. ' WHEN pwrx.wake_reason=2 THEN \'Timer Deadline\''
  650. ' WHEN pwrx.wake_reason=4 THEN \'Monitored Address\''
  651. ' WHEN pwrx.wake_reason=8 THEN \'HW\''
  652. ' ELSE FORMAT(\'%2s\', pwrx.wake_reason)'
  653. 'END AS wake_reason'
  654. ' FROM cbr'
  655. ' FULL JOIN mwait ON mwait.id = cbr.id'
  656. ' FULL JOIN pwre ON pwre.id = cbr.id'
  657. ' FULL JOIN exstop ON exstop.id = cbr.id'
  658. ' FULL JOIN pwrx ON pwrx.id = cbr.id'
  659. ' INNER JOIN samples ON samples.id = coalesce(cbr.id, mwait.id, pwre.id, exstop.id, pwrx.id)'
  660. ' INNER JOIN selected_events ON selected_events.id = samples.evsel_id'
  661. ' ORDER BY samples.id')
  662. do_query(query, 'CREATE VIEW context_switches_view AS '
  663. 'SELECT '
  664. 'context_switches.id,'
  665. 'context_switches.machine_id,'
  666. 'context_switches.time,'
  667. 'context_switches.cpu,'
  668. 'th_out.pid AS pid_out,'
  669. 'th_out.tid AS tid_out,'
  670. 'comm_out.comm AS comm_out,'
  671. 'th_in.pid AS pid_in,'
  672. 'th_in.tid AS tid_in,'
  673. 'comm_in.comm AS comm_in,'
  674. 'CASE WHEN context_switches.flags = 0 THEN \'in\''
  675. ' WHEN context_switches.flags = 1 THEN \'out\''
  676. ' WHEN context_switches.flags = 3 THEN \'out preempt\''
  677. ' ELSE CAST ( context_switches.flags AS VARCHAR(11) )'
  678. 'END AS flags'
  679. ' FROM context_switches'
  680. ' INNER JOIN threads AS th_out ON th_out.id = context_switches.thread_out_id'
  681. ' INNER JOIN threads AS th_in ON th_in.id = context_switches.thread_in_id'
  682. ' INNER JOIN comms AS comm_out ON comm_out.id = context_switches.comm_out_id'
  683. ' INNER JOIN comms AS comm_in ON comm_in.id = context_switches.comm_in_id')
  684. file_header = struct.pack("!11sii", b"PGCOPY\n\377\r\n\0", 0, 0)
  685. file_trailer = b"\377\377"
  686. def open_output_file(file_name):
  687. path_name = output_dir_name + "/" + file_name
  688. file = open(path_name, "wb+")
  689. file.write(file_header)
  690. return file
  691. def close_output_file(file):
  692. file.write(file_trailer)
  693. file.close()
  694. def copy_output_file_direct(file, table_name):
  695. close_output_file(file)
  696. sql = "COPY " + table_name + " FROM '" + file.name + "' (FORMAT 'binary')"
  697. do_query(query, sql)
  698. # Use COPY FROM STDIN because security may prevent postgres from accessing the files directly
  699. def copy_output_file(file, table_name):
  700. conn = PQconnectdb(toclientstr("dbname = " + dbname))
  701. if (PQstatus(conn)):
  702. raise Exception("COPY FROM STDIN PQconnectdb failed")
  703. file.write(file_trailer)
  704. file.seek(0)
  705. sql = "COPY " + table_name + " FROM STDIN (FORMAT 'binary')"
  706. res = PQexec(conn, toclientstr(sql))
  707. if (PQresultStatus(res) != 4):
  708. raise Exception("COPY FROM STDIN PQexec failed")
  709. data = file.read(65536)
  710. while (len(data)):
  711. ret = PQputCopyData(conn, data, len(data))
  712. if (ret != 1):
  713. raise Exception("COPY FROM STDIN PQputCopyData failed, error " + str(ret))
  714. data = file.read(65536)
  715. ret = PQputCopyEnd(conn, None)
  716. if (ret != 1):
  717. raise Exception("COPY FROM STDIN PQputCopyEnd failed, error " + str(ret))
  718. PQfinish(conn)
  719. def remove_output_file(file):
  720. name = file.name
  721. file.close()
  722. os.unlink(name)
  723. evsel_file = open_output_file("evsel_table.bin")
  724. machine_file = open_output_file("machine_table.bin")
  725. thread_file = open_output_file("thread_table.bin")
  726. comm_file = open_output_file("comm_table.bin")
  727. comm_thread_file = open_output_file("comm_thread_table.bin")
  728. dso_file = open_output_file("dso_table.bin")
  729. symbol_file = open_output_file("symbol_table.bin")
  730. branch_type_file = open_output_file("branch_type_table.bin")
  731. sample_file = open_output_file("sample_table.bin")
  732. if perf_db_export_calls or perf_db_export_callchains:
  733. call_path_file = open_output_file("call_path_table.bin")
  734. if perf_db_export_calls:
  735. call_file = open_output_file("call_table.bin")
  736. ptwrite_file = open_output_file("ptwrite_table.bin")
  737. cbr_file = open_output_file("cbr_table.bin")
  738. mwait_file = open_output_file("mwait_table.bin")
  739. pwre_file = open_output_file("pwre_table.bin")
  740. exstop_file = open_output_file("exstop_table.bin")
  741. pwrx_file = open_output_file("pwrx_table.bin")
  742. context_switches_file = open_output_file("context_switches_table.bin")
  743. def trace_begin():
  744. printdate("Writing to intermediate files...")
  745. # id == 0 means unknown. It is easier to create records for them than replace the zeroes with NULLs
  746. evsel_table(0, "unknown")
  747. machine_table(0, 0, "unknown")
  748. thread_table(0, 0, 0, -1, -1)
  749. comm_table(0, "unknown", 0, 0, 0)
  750. dso_table(0, 0, "unknown", "unknown", "")
  751. symbol_table(0, 0, 0, 0, 0, "unknown")
  752. 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, 0)
  753. if perf_db_export_calls or perf_db_export_callchains:
  754. call_path_table(0, 0, 0, 0)
  755. call_return_table(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
  756. unhandled_count = 0
  757. def is_table_empty(table_name):
  758. do_query(query, 'SELECT * FROM ' + table_name + ' LIMIT 1');
  759. if query.next():
  760. return False
  761. return True
  762. def drop(table_name):
  763. do_query(query, 'DROP VIEW ' + table_name + '_view');
  764. do_query(query, 'DROP TABLE ' + table_name);
  765. def trace_end():
  766. printdate("Copying to database...")
  767. copy_output_file(evsel_file, "selected_events")
  768. copy_output_file(machine_file, "machines")
  769. copy_output_file(thread_file, "threads")
  770. copy_output_file(comm_file, "comms")
  771. copy_output_file(comm_thread_file, "comm_threads")
  772. copy_output_file(dso_file, "dsos")
  773. copy_output_file(symbol_file, "symbols")
  774. copy_output_file(branch_type_file, "branch_types")
  775. copy_output_file(sample_file, "samples")
  776. if perf_db_export_calls or perf_db_export_callchains:
  777. copy_output_file(call_path_file, "call_paths")
  778. if perf_db_export_calls:
  779. copy_output_file(call_file, "calls")
  780. copy_output_file(ptwrite_file, "ptwrite")
  781. copy_output_file(cbr_file, "cbr")
  782. copy_output_file(mwait_file, "mwait")
  783. copy_output_file(pwre_file, "pwre")
  784. copy_output_file(exstop_file, "exstop")
  785. copy_output_file(pwrx_file, "pwrx")
  786. copy_output_file(context_switches_file, "context_switches")
  787. printdate("Removing intermediate files...")
  788. remove_output_file(evsel_file)
  789. remove_output_file(machine_file)
  790. remove_output_file(thread_file)
  791. remove_output_file(comm_file)
  792. remove_output_file(comm_thread_file)
  793. remove_output_file(dso_file)
  794. remove_output_file(symbol_file)
  795. remove_output_file(branch_type_file)
  796. remove_output_file(sample_file)
  797. if perf_db_export_calls or perf_db_export_callchains:
  798. remove_output_file(call_path_file)
  799. if perf_db_export_calls:
  800. remove_output_file(call_file)
  801. remove_output_file(ptwrite_file)
  802. remove_output_file(cbr_file)
  803. remove_output_file(mwait_file)
  804. remove_output_file(pwre_file)
  805. remove_output_file(exstop_file)
  806. remove_output_file(pwrx_file)
  807. remove_output_file(context_switches_file)
  808. os.rmdir(output_dir_name)
  809. printdate("Adding primary keys")
  810. do_query(query, 'ALTER TABLE selected_events ADD PRIMARY KEY (id)')
  811. do_query(query, 'ALTER TABLE machines ADD PRIMARY KEY (id)')
  812. do_query(query, 'ALTER TABLE threads ADD PRIMARY KEY (id)')
  813. do_query(query, 'ALTER TABLE comms ADD PRIMARY KEY (id)')
  814. do_query(query, 'ALTER TABLE comm_threads ADD PRIMARY KEY (id)')
  815. do_query(query, 'ALTER TABLE dsos ADD PRIMARY KEY (id)')
  816. do_query(query, 'ALTER TABLE symbols ADD PRIMARY KEY (id)')
  817. do_query(query, 'ALTER TABLE branch_types ADD PRIMARY KEY (id)')
  818. do_query(query, 'ALTER TABLE samples ADD PRIMARY KEY (id)')
  819. if perf_db_export_calls or perf_db_export_callchains:
  820. do_query(query, 'ALTER TABLE call_paths ADD PRIMARY KEY (id)')
  821. if perf_db_export_calls:
  822. do_query(query, 'ALTER TABLE calls ADD PRIMARY KEY (id)')
  823. do_query(query, 'ALTER TABLE ptwrite ADD PRIMARY KEY (id)')
  824. do_query(query, 'ALTER TABLE cbr ADD PRIMARY KEY (id)')
  825. do_query(query, 'ALTER TABLE mwait ADD PRIMARY KEY (id)')
  826. do_query(query, 'ALTER TABLE pwre ADD PRIMARY KEY (id)')
  827. do_query(query, 'ALTER TABLE exstop ADD PRIMARY KEY (id)')
  828. do_query(query, 'ALTER TABLE pwrx ADD PRIMARY KEY (id)')
  829. do_query(query, 'ALTER TABLE context_switches ADD PRIMARY KEY (id)')
  830. printdate("Adding foreign keys")
  831. do_query(query, 'ALTER TABLE threads '
  832. 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),'
  833. 'ADD CONSTRAINT processfk FOREIGN KEY (process_id) REFERENCES threads (id)')
  834. do_query(query, 'ALTER TABLE comms '
  835. 'ADD CONSTRAINT threadfk FOREIGN KEY (c_thread_id) REFERENCES threads (id)')
  836. do_query(query, 'ALTER TABLE comm_threads '
  837. 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
  838. 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id)')
  839. do_query(query, 'ALTER TABLE dsos '
  840. 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id)')
  841. do_query(query, 'ALTER TABLE symbols '
  842. 'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id)')
  843. do_query(query, 'ALTER TABLE samples '
  844. 'ADD CONSTRAINT evselfk FOREIGN KEY (evsel_id) REFERENCES selected_events (id),'
  845. 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),'
  846. 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),'
  847. 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
  848. 'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id),'
  849. 'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id),'
  850. 'ADD CONSTRAINT todsofk FOREIGN KEY (to_dso_id) REFERENCES dsos (id),'
  851. 'ADD CONSTRAINT tosymbolfk FOREIGN KEY (to_symbol_id) REFERENCES symbols (id)')
  852. if perf_db_export_calls or perf_db_export_callchains:
  853. do_query(query, 'ALTER TABLE call_paths '
  854. 'ADD CONSTRAINT parentfk FOREIGN KEY (parent_id) REFERENCES call_paths (id),'
  855. 'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id)')
  856. if perf_db_export_calls:
  857. do_query(query, 'ALTER TABLE calls '
  858. 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),'
  859. 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),'
  860. 'ADD CONSTRAINT call_pathfk FOREIGN KEY (call_path_id) REFERENCES call_paths (id),'
  861. 'ADD CONSTRAINT callfk FOREIGN KEY (call_id) REFERENCES samples (id),'
  862. 'ADD CONSTRAINT returnfk FOREIGN KEY (return_id) REFERENCES samples (id),'
  863. 'ADD CONSTRAINT parent_call_pathfk FOREIGN KEY (parent_call_path_id) REFERENCES call_paths (id)')
  864. do_query(query, 'CREATE INDEX pcpid_idx ON calls (parent_call_path_id)')
  865. do_query(query, 'CREATE INDEX pid_idx ON calls (parent_id)')
  866. do_query(query, 'ALTER TABLE comms ADD has_calls boolean')
  867. do_query(query, 'UPDATE comms SET has_calls = TRUE WHERE comms.id IN (SELECT DISTINCT comm_id FROM calls)')
  868. do_query(query, 'ALTER TABLE ptwrite '
  869. 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
  870. do_query(query, 'ALTER TABLE cbr '
  871. 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
  872. do_query(query, 'ALTER TABLE mwait '
  873. 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
  874. do_query(query, 'ALTER TABLE pwre '
  875. 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
  876. do_query(query, 'ALTER TABLE exstop '
  877. 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
  878. do_query(query, 'ALTER TABLE pwrx '
  879. 'ADD CONSTRAINT idfk FOREIGN KEY (id) REFERENCES samples (id)')
  880. do_query(query, 'ALTER TABLE context_switches '
  881. 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),'
  882. 'ADD CONSTRAINT toutfk FOREIGN KEY (thread_out_id) REFERENCES threads (id),'
  883. 'ADD CONSTRAINT tinfk FOREIGN KEY (thread_in_id) REFERENCES threads (id),'
  884. 'ADD CONSTRAINT coutfk FOREIGN KEY (comm_out_id) REFERENCES comms (id),'
  885. 'ADD CONSTRAINT cinfk FOREIGN KEY (comm_in_id) REFERENCES comms (id)')
  886. printdate("Dropping unused tables")
  887. if is_table_empty("ptwrite"):
  888. drop("ptwrite")
  889. if is_table_empty("mwait") and is_table_empty("pwre") and is_table_empty("exstop") and is_table_empty("pwrx"):
  890. do_query(query, 'DROP VIEW power_events_view');
  891. drop("mwait")
  892. drop("pwre")
  893. drop("exstop")
  894. drop("pwrx")
  895. if is_table_empty("cbr"):
  896. drop("cbr")
  897. if is_table_empty("context_switches"):
  898. drop("context_switches")
  899. if (unhandled_count):
  900. printdate("Warning: ", unhandled_count, " unhandled events")
  901. printdate("Done")
  902. def trace_unhandled(event_name, context, event_fields_dict):
  903. global unhandled_count
  904. unhandled_count += 1
  905. def sched__sched_switch(*x):
  906. pass
  907. def evsel_table(evsel_id, evsel_name, *x):
  908. evsel_name = toserverstr(evsel_name)
  909. n = len(evsel_name)
  910. fmt = "!hiqi" + str(n) + "s"
  911. value = struct.pack(fmt, 2, 8, evsel_id, n, evsel_name)
  912. evsel_file.write(value)
  913. def machine_table(machine_id, pid, root_dir, *x):
  914. root_dir = toserverstr(root_dir)
  915. n = len(root_dir)
  916. fmt = "!hiqiii" + str(n) + "s"
  917. value = struct.pack(fmt, 3, 8, machine_id, 4, pid, n, root_dir)
  918. machine_file.write(value)
  919. def thread_table(thread_id, machine_id, process_id, pid, tid, *x):
  920. value = struct.pack("!hiqiqiqiiii", 5, 8, thread_id, 8, machine_id, 8, process_id, 4, pid, 4, tid)
  921. thread_file.write(value)
  922. def comm_table(comm_id, comm_str, thread_id, time, exec_flag, *x):
  923. comm_str = toserverstr(comm_str)
  924. n = len(comm_str)
  925. fmt = "!hiqi" + str(n) + "s" + "iqiqiB"
  926. value = struct.pack(fmt, 5, 8, comm_id, n, comm_str, 8, thread_id, 8, time, 1, exec_flag)
  927. comm_file.write(value)
  928. def comm_thread_table(comm_thread_id, comm_id, thread_id, *x):
  929. fmt = "!hiqiqiq"
  930. value = struct.pack(fmt, 3, 8, comm_thread_id, 8, comm_id, 8, thread_id)
  931. comm_thread_file.write(value)
  932. def dso_table(dso_id, machine_id, short_name, long_name, build_id, *x):
  933. short_name = toserverstr(short_name)
  934. long_name = toserverstr(long_name)
  935. build_id = toserverstr(build_id)
  936. n1 = len(short_name)
  937. n2 = len(long_name)
  938. n3 = len(build_id)
  939. fmt = "!hiqiqi" + str(n1) + "si" + str(n2) + "si" + str(n3) + "s"
  940. value = struct.pack(fmt, 5, 8, dso_id, 8, machine_id, n1, short_name, n2, long_name, n3, build_id)
  941. dso_file.write(value)
  942. def symbol_table(symbol_id, dso_id, sym_start, sym_end, binding, symbol_name, *x):
  943. symbol_name = toserverstr(symbol_name)
  944. n = len(symbol_name)
  945. fmt = "!hiqiqiqiqiii" + str(n) + "s"
  946. value = struct.pack(fmt, 6, 8, symbol_id, 8, dso_id, 8, sym_start, 8, sym_end, 4, binding, n, symbol_name)
  947. symbol_file.write(value)
  948. def branch_type_table(branch_type, name, *x):
  949. name = toserverstr(name)
  950. n = len(name)
  951. fmt = "!hiii" + str(n) + "s"
  952. value = struct.pack(fmt, 2, 4, branch_type, n, name)
  953. branch_type_file.write(value)
  954. 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, flags, *x):
  955. if branches:
  956. value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiiiBiqiqiqii", 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, 4, branch_type, 1, in_tx, 8, call_path_id, 8, insn_cnt, 8, cyc_cnt, 4, flags)
  957. else:
  958. value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiqiqiqiqiiiBiqiqiqii", 25, 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, 4, flags)
  959. sample_file.write(value)
  960. def call_path_table(cp_id, parent_id, symbol_id, ip, *x):
  961. fmt = "!hiqiqiqiq"
  962. value = struct.pack(fmt, 4, 8, cp_id, 8, parent_id, 8, symbol_id, 8, ip)
  963. call_path_file.write(value)
  964. 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):
  965. fmt = "!hiqiqiqiqiqiqiqiqiqiqiiiqiqiq"
  966. 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)
  967. call_file.write(value)
  968. def ptwrite(id, raw_buf):
  969. data = struct.unpack_from("<IQ", raw_buf)
  970. flags = data[0]
  971. payload = data[1]
  972. exact_ip = flags & 1
  973. value = struct.pack("!hiqiqiB", 3, 8, id, 8, payload, 1, exact_ip)
  974. ptwrite_file.write(value)
  975. def cbr(id, raw_buf):
  976. data = struct.unpack_from("<BBBBII", raw_buf)
  977. cbr = data[0]
  978. MHz = (data[4] + 500) / 1000
  979. percent = ((cbr * 1000 / data[2]) + 5) / 10
  980. value = struct.pack("!hiqiiiiii", 4, 8, id, 4, cbr, 4, int(MHz), 4, int(percent))
  981. cbr_file.write(value)
  982. def mwait(id, raw_buf):
  983. data = struct.unpack_from("<IQ", raw_buf)
  984. payload = data[1]
  985. hints = payload & 0xff
  986. extensions = (payload >> 32) & 0x3
  987. value = struct.pack("!hiqiiii", 3, 8, id, 4, hints, 4, extensions)
  988. mwait_file.write(value)
  989. def pwre(id, raw_buf):
  990. data = struct.unpack_from("<IQ", raw_buf)
  991. payload = data[1]
  992. hw = (payload >> 7) & 1
  993. cstate = (payload >> 12) & 0xf
  994. subcstate = (payload >> 8) & 0xf
  995. value = struct.pack("!hiqiiiiiB", 4, 8, id, 4, cstate, 4, subcstate, 1, hw)
  996. pwre_file.write(value)
  997. def exstop(id, raw_buf):
  998. data = struct.unpack_from("<I", raw_buf)
  999. flags = data[0]
  1000. exact_ip = flags & 1
  1001. value = struct.pack("!hiqiB", 2, 8, id, 1, exact_ip)
  1002. exstop_file.write(value)
  1003. def pwrx(id, raw_buf):
  1004. data = struct.unpack_from("<IQ", raw_buf)
  1005. payload = data[1]
  1006. deepest_cstate = payload & 0xf
  1007. last_cstate = (payload >> 4) & 0xf
  1008. wake_reason = (payload >> 8) & 0xf
  1009. value = struct.pack("!hiqiiiiii", 4, 8, id, 4, deepest_cstate, 4, last_cstate, 4, wake_reason)
  1010. pwrx_file.write(value)
  1011. def synth_data(id, config, raw_buf, *x):
  1012. if config == 0:
  1013. ptwrite(id, raw_buf)
  1014. elif config == 1:
  1015. mwait(id, raw_buf)
  1016. elif config == 2:
  1017. pwre(id, raw_buf)
  1018. elif config == 3:
  1019. exstop(id, raw_buf)
  1020. elif config == 4:
  1021. pwrx(id, raw_buf)
  1022. elif config == 5:
  1023. cbr(id, raw_buf)
  1024. def context_switch_table(id, machine_id, time, cpu, thread_out_id, comm_out_id, thread_in_id, comm_in_id, flags, *x):
  1025. fmt = "!hiqiqiqiiiqiqiqiqii"
  1026. value = struct.pack(fmt, 9, 8, id, 8, machine_id, 8, time, 4, cpu, 8, thread_out_id, 8, comm_out_id, 8, thread_in_id, 8, comm_in_id, 4, flags)
  1027. context_switches_file.write(value)