callgraph_utils.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. // Copyright (c) 2009 Facebook
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. /*
  17. * This file contains callgraph image generation related XHProf utility
  18. * functions
  19. *
  20. */
  21. // Supported ouput format
  22. $xhprof_legal_image_types = array(
  23. "jpg" => 1,
  24. "gif" => 1,
  25. "png" => 1,
  26. "ps" => 1,
  27. );
  28. /**
  29. * Send an HTTP header with the response. You MUST use this function instead
  30. * of header() so that we can debug header issues because they're virtually
  31. * impossible to debug otherwise. If you try to commit header(), SVN will
  32. * reject your commit.
  33. *
  34. * @param string HTTP header name, like 'Location'
  35. * @param string HTTP header value, like 'http://www.example.com/'
  36. *
  37. */
  38. function xhprof_http_header($name, $value) {
  39. if (!$name) {
  40. xhprof_error('http_header usage');
  41. return null;
  42. }
  43. if (!is_string($value)) {
  44. xhprof_error('http_header value not a string');
  45. }
  46. header($name.': '.$value, true);
  47. }
  48. /**
  49. * Genearte and send MIME header for the output image to client browser.
  50. *
  51. * @author cjiang
  52. */
  53. function xhprof_generate_mime_header($type, $length) {
  54. switch ($type) {
  55. case 'jpg':
  56. $mime = 'image/jpeg';
  57. break;
  58. case 'gif':
  59. $mime = 'image/gif';
  60. break;
  61. case 'png':
  62. $mime = 'image/png';
  63. break;
  64. case 'ps':
  65. $mime = 'application/postscript';
  66. default:
  67. $mime = false;
  68. }
  69. if ($mime) {
  70. xhprof_http_header('Content-type', $mime);
  71. xhprof_http_header('Content-length', (string)$length);
  72. }
  73. }
  74. /**
  75. * Generate image according to DOT script. This function will spawn a process
  76. * with "dot" command and pipe the "dot_script" to it and pipe out the
  77. * generated image content.
  78. *
  79. * @param dot_script, string, the script for DOT to generate the image.
  80. * @param type, one of the supported image types, see
  81. * $xhprof_legal_image_types.
  82. * @return binary content of the generated image on success. empty string on
  83. * failure.
  84. *
  85. * @author cjiang
  86. */
  87. function xhprof_generate_image_by_dot($dot_script, $type) {
  88. $descriptorspec = array(
  89. // stdin is a pipe that the child will read from
  90. 0 => array("pipe", "r"),
  91. // stdout is a pipe that the child will write to
  92. 1 => array("pipe", "w"),
  93. // stderr is a file to write to
  94. 2 => array("file", "/dev/null", "a")
  95. );
  96. $cmd = " dot -T".$type;
  97. $process = proc_open($cmd, $descriptorspec, $pipes, "/tmp", array());
  98. if (is_resource($process)) {
  99. fwrite($pipes[0], $dot_script);
  100. fclose($pipes[0]);
  101. $output = stream_get_contents($pipes[1]);
  102. fclose($pipes[1]);
  103. proc_close($process);
  104. return $output;
  105. }
  106. print "failed to shell execute cmd=\"$cmd\"\n";
  107. exit();
  108. }
  109. /*
  110. * Get the children list of all nodes.
  111. */
  112. function xhprof_get_children_table($raw_data) {
  113. $children_table = array();
  114. foreach ($raw_data as $parent_child => $info) {
  115. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  116. if (!isset($children_table[$parent])) {
  117. $children_table[$parent] = array($child);
  118. } else {
  119. $children_table[$parent][] = $child;
  120. }
  121. }
  122. return $children_table;
  123. }
  124. /**
  125. * Generate DOT script from the given raw phprof data.
  126. *
  127. * @param raw_data, phprof profile data.
  128. * @param threshold, float, the threshold value [0,1). The functions in the
  129. * raw_data whose exclusive wall times ratio are below the
  130. * threshold will be filtered out and won't apprear in the
  131. * generated image.
  132. * @param page, string(optional), the root node name. This can be used to
  133. * replace the 'main()' as the root node.
  134. * @param func, string, the focus function.
  135. * @param critical_path, bool, whether or not to display critical path with
  136. * bold lines.
  137. * @return string, the DOT script to generate image.
  138. *
  139. * @author cjiang
  140. */
  141. function xhprof_generate_dot_script($raw_data, $threshold, $source, $page,
  142. $func, $critical_path, $right=null,
  143. $left=null) {
  144. $max_width = 5;
  145. $max_height = 3.5;
  146. $max_fontsize = 35;
  147. $max_sizing_ratio = 20;
  148. $totals;
  149. if ($left === null) {
  150. // init_metrics($raw_data, null, null);
  151. }
  152. $sym_table = xhprof_compute_flat_info($raw_data, $totals);
  153. if ($critical_path) {
  154. $children_table = xhprof_get_children_table($raw_data);
  155. $node = "main()";
  156. $path = array();
  157. $path_edges = array();
  158. $visited = array();
  159. while ($node) {
  160. $visited[$node] = true;
  161. if (isset($children_table[$node])) {
  162. $max_child = null;
  163. foreach ($children_table[$node] as $child) {
  164. if (isset($visited[$child])) {
  165. continue;
  166. }
  167. if ($max_child === null ||
  168. abs($raw_data[xhprof_build_parent_child_key($node,
  169. $child)]["wt"]) >
  170. abs($raw_data[xhprof_build_parent_child_key($node,
  171. $max_child)]["wt"])) {
  172. $max_child = $child;
  173. }
  174. }
  175. if ($max_child !== null) {
  176. $path[$max_child] = true;
  177. $path_edges[xhprof_build_parent_child_key($node, $max_child)] = true;
  178. }
  179. $node = $max_child;
  180. } else {
  181. $node = null;
  182. }
  183. }
  184. }
  185. // if it is a benchmark callgraph, we make the benchmarked function the root.
  186. if ($source == "bm" && array_key_exists("main()", $sym_table)) {
  187. $total_times = $sym_table["main()"]["ct"];
  188. $remove_funcs = array("main()",
  189. "hotprofiler_disable",
  190. "call_user_func_array",
  191. "xhprof_disable");
  192. foreach ($remove_funcs as $cur_del_func) {
  193. if (array_key_exists($cur_del_func, $sym_table) &&
  194. $sym_table[$cur_del_func]["ct"] == $total_times) {
  195. unset($sym_table[$cur_del_func]);
  196. }
  197. }
  198. }
  199. // use the function to filter out irrelevant functions.
  200. if (!empty($func)) {
  201. $interested_funcs = array();
  202. foreach ($raw_data as $parent_child => $info) {
  203. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  204. if ($parent == $func || $child == $func) {
  205. $interested_funcs[$parent] = 1;
  206. $interested_funcs[$child] = 1;
  207. }
  208. }
  209. foreach ($sym_table as $symbol => $info) {
  210. if (!array_key_exists($symbol, $interested_funcs)) {
  211. unset($sym_table[$symbol]);
  212. }
  213. }
  214. }
  215. $result = "digraph call_graph {\n";
  216. // Filter out functions whose exclusive time ratio is below threshold, and
  217. // also assign a unique integer id for each function to be generated. In the
  218. // meantime, find the function with the most exclusive time (potentially the
  219. // performance bottleneck).
  220. $cur_id = 0; $max_wt = 0;
  221. foreach ($sym_table as $symbol => $info) {
  222. if (empty($func) && abs($info["wt"] / $totals["wt"]) < $threshold) {
  223. unset($sym_table[$symbol]);
  224. continue;
  225. }
  226. if ($max_wt == 0 || $max_wt < abs($info["excl_wt"])) {
  227. $max_wt = abs($info["excl_wt"]);
  228. }
  229. $sym_table[$symbol]["id"] = $cur_id;
  230. $cur_id ++;
  231. }
  232. // Generate all nodes' information.
  233. foreach ($sym_table as $symbol => $info) {
  234. if ($info["excl_wt"] == 0) {
  235. $sizing_factor = $max_sizing_ratio;
  236. } else {
  237. $sizing_factor = $max_wt / abs($info["excl_wt"]) ;
  238. if ($sizing_factor > $max_sizing_ratio) {
  239. $sizing_factor = $max_sizing_ratio;
  240. }
  241. }
  242. $fillcolor = (($sizing_factor < 1.5) ?
  243. ", style=filled, fillcolor=red" : "");
  244. if ($critical_path) {
  245. // highlight nodes along critical path.
  246. if (!$fillcolor && array_key_exists($symbol, $path)) {
  247. $fillcolor = ", style=filled, fillcolor=yellow";
  248. }
  249. }
  250. $fontsize =", fontsize="
  251. .(int)($max_fontsize / (($sizing_factor - 1) / 10 + 1));
  252. $width = ", width=".sprintf("%.1f", $max_width / $sizing_factor);
  253. $height = ", height=".sprintf("%.1f", $max_height / $sizing_factor);
  254. if ($symbol == "main()") {
  255. $shape = "octagon";
  256. $name ="Total: ".($totals["wt"]/1000.0)." ms\\n";
  257. $name .= addslashes(isset($page) ? $page : $symbol);
  258. } else {
  259. $shape = "box";
  260. $name = addslashes($symbol)."\\nInc: ". sprintf("%.3f",$info["wt"]/1000) .
  261. " ms (" . sprintf("%.1f%%", 100 * $info["wt"]/$totals["wt"]).")";
  262. }
  263. if ($left === null) {
  264. $label = ", label=\"".$name."\\nExcl: "
  265. .(sprintf("%.3f",$info["excl_wt"]/1000.0))." ms ("
  266. .sprintf("%.1f%%", 100 * $info["excl_wt"]/$totals["wt"])
  267. . ")\\n".$info["ct"]." total calls\"";
  268. } else {
  269. if (isset($left[$symbol]) && isset($right[$symbol])) {
  270. $label = ", label=\"".addslashes($symbol).
  271. "\\nInc: ".(sprintf("%.3f",$left[$symbol]["wt"]/1000.0))
  272. ." ms - "
  273. .(sprintf("%.3f",$right[$symbol]["wt"]/1000.0))." ms = "
  274. .(sprintf("%.3f",$info["wt"]/1000.0))." ms".
  275. "\\nExcl: "
  276. .(sprintf("%.3f",$left[$symbol]["excl_wt"]/1000.0))
  277. ." ms - ".(sprintf("%.3f",$right[$symbol]["excl_wt"]/1000.0))
  278. ." ms = ".(sprintf("%.3f",$info["excl_wt"]/1000.0))." ms".
  279. "\\nCalls: ".(sprintf("%.3f",$left[$symbol]["ct"]))." - "
  280. .(sprintf("%.3f",$right[$symbol]["ct"]))." = "
  281. .(sprintf("%.3f",$info["ct"]))."\"";
  282. } else if (isset($left[$symbol])) {
  283. $label = ", label=\"".addslashes($symbol).
  284. "\\nInc: ".(sprintf("%.3f",$left[$symbol]["wt"]/1000.0))
  285. ." ms - 0 ms = ".(sprintf("%.3f",$info["wt"]/1000.0))
  286. ." ms"."\\nExcl: "
  287. .(sprintf("%.3f",$left[$symbol]["excl_wt"]/1000.0))
  288. ." ms - 0 ms = "
  289. .(sprintf("%.3f",$info["excl_wt"]/1000.0))." ms".
  290. "\\nCalls: ".(sprintf("%.3f",$left[$symbol]["ct"]))." - 0 = "
  291. .(sprintf("%.3f",$info["ct"]))."\"";
  292. } else {
  293. $label = ", label=\"".addslashes($symbol).
  294. "\\nInc: 0 ms - "
  295. .(sprintf("%.3f",$right[$symbol]["wt"]/1000.0))
  296. ." ms = ".(sprintf("%.3f",$info["wt"]/1000.0))." ms".
  297. "\\nExcl: 0 ms - "
  298. .(sprintf("%.3f",$right[$symbol]["excl_wt"]/1000.0))
  299. ." ms = ".(sprintf("%.3f",$info["excl_wt"]/1000.0))." ms".
  300. "\\nCalls: 0 - ".(sprintf("%.3f",$right[$symbol]["ct"]))
  301. ." = ".(sprintf("%.3f",$info["ct"]))."\"";
  302. }
  303. }
  304. $result .= "N" . $sym_table[$symbol]["id"];
  305. $result .= "[shape=$shape ".$label.$width
  306. .$height.$fontsize.$fillcolor."];\n";
  307. }
  308. // Generate all the edges' information.
  309. foreach ($raw_data as $parent_child => $info) {
  310. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  311. if (isset($sym_table[$parent]) && isset($sym_table[$child]) &&
  312. (empty($func) ||
  313. (!empty($func) && ($parent == $func || $child == $func)) )) {
  314. $label = $info["ct"] == 1 ? $info["ct"]." call" : $info["ct"]." calls";
  315. $headlabel = $sym_table[$child]["wt"] > 0 ?
  316. sprintf("%.1f%%", 100 * $info["wt"]
  317. / $sym_table[$child]["wt"])
  318. : "0.0%";
  319. $taillabel = ($sym_table[$parent]["wt"] > 0) ?
  320. sprintf("%.1f%%",
  321. 100 * $info["wt"] /
  322. ($sym_table[$parent]["wt"] - $sym_table["$parent"]["excl_wt"]))
  323. : "0.0%";
  324. $linewidth= 1;
  325. $arrow_size = 1;
  326. if ($critical_path &&
  327. isset($path_edges[xhprof_build_parent_child_key($parent, $child)])) {
  328. $linewidth = 10; $arrow_size=2;
  329. }
  330. $result .= "N" . $sym_table[$parent]["id"] . " -> N"
  331. . $sym_table[$child]["id"];
  332. $result .= "[arrowsize=$arrow_size, style=\"setlinewidth($linewidth)\","
  333. ." label=\""
  334. .$label."\", headlabel=\"".$headlabel
  335. ."\", taillabel=\"".$taillabel."\" ]";
  336. $result .= ";\n";
  337. }
  338. }
  339. $result = $result . "\n}";
  340. return $result;
  341. }
  342. function xhprof_render_diff_image($xhprof_runs_impl, $run1, $run2,
  343. $type, $threshold, $source) {
  344. $total1;
  345. $total2;
  346. $raw_data1 = $xhprof_runs_impl->get_run($run1, $source, $desc_unused);
  347. $raw_data2 = $xhprof_runs_impl->get_run($run2, $source, $desc_unused);
  348. // init_metrics($raw_data1, null, null);
  349. $children_table1 = xhprof_get_children_table($raw_data1);
  350. $children_table2 = xhprof_get_children_table($raw_data2);
  351. $symbol_tab1 = xhprof_compute_flat_info($raw_data1, $total1);
  352. $symbol_tab2 = xhprof_compute_flat_info($raw_data2, $total2);
  353. $run_delta = xhprof_compute_diff($raw_data1, $raw_data2);
  354. $script = xhprof_generate_dot_script($run_delta, $threshold, $source,
  355. null, null, true,
  356. $symbol_tab1, $symbol_tab2);
  357. $content = xhprof_generate_image_by_dot($script, $type);
  358. xhprof_generate_mime_header($type, strlen($content));
  359. echo $content;
  360. }
  361. /**
  362. * Generate image content from phprof run id.
  363. *
  364. * @param object $xhprof_runs_impl An object that implements
  365. * the iXHProfRuns interface
  366. * @param run_id, integer, the unique id for the phprof run, this is the
  367. * primary key for phprof database table.
  368. * @param type, string, one of the supported image types. See also
  369. * $xhprof_legal_image_types.
  370. * @param threshold, float, the threshold value [0,1). The functions in the
  371. * raw_data whose exclusive wall times ratio are below the
  372. * threshold will be filtered out and won't apprear in the
  373. * generated image.
  374. * @param func, string, the focus function.
  375. * @return string, the DOT script to generate image.
  376. *
  377. * @author cjiang
  378. */
  379. function xhprof_get_content_by_run($xhprof_runs_impl, $run_id, $type,
  380. $threshold, $func, $source,
  381. $critical_path) {
  382. if (!$run_id)
  383. return "";
  384. $raw_data = $xhprof_runs_impl->get_run($run_id, $source, $description);
  385. if (!$raw_data) {
  386. xhprof_error("Raw data is empty");
  387. return "";
  388. }
  389. $script = xhprof_generate_dot_script($raw_data, $threshold, $source,
  390. $description, $func, $critical_path);
  391. $content = xhprof_generate_image_by_dot($script, $type);
  392. return $content;
  393. }
  394. /**
  395. * Generate image from phprof run id and send it to client.
  396. *
  397. * @param object $xhprof_runs_impl An object that implements
  398. * the iXHProfRuns interface
  399. * @param run_id, integer, the unique id for the phprof run, this is the
  400. * primary key for phprof database table.
  401. * @param type, string, one of the supported image types. See also
  402. * $xhprof_legal_image_types.
  403. * @param threshold, float, the threshold value [0,1). The functions in the
  404. * raw_data whose exclusive wall times ratio are below the
  405. * threshold will be filtered out and won't apprear in the
  406. * generated image.
  407. * @param func, string, the focus function.
  408. * @param bool, does this run correspond to a PHProfLive run or a dev run?
  409. * @author cjiang
  410. */
  411. function xhprof_render_image($xhprof_runs_impl, $run_id, $type, $threshold,
  412. $func, $source, $critical_path) {
  413. $content = xhprof_get_content_by_run($xhprof_runs_impl, $run_id, $type,
  414. $threshold,
  415. $func, $source, $critical_path);
  416. if (!$content) {
  417. print "Error: either we can not find profile data for run_id ".$run_id
  418. ." or the threshold ".$threshold." is too small or you do not"
  419. ." have 'dot' image generation utility installed.";
  420. exit();
  421. }
  422. xhprof_generate_mime_header($type, strlen($content));
  423. echo $content;
  424. }