performance.module

Tracking 5.x-1.x branch
  1. drupal
    1. 5 contributions/devel/performance/performance.module

Functions & methods

NameDescription
performance_apc_list_all
performance_clear_apc_confirm
performance_clear_apc_confirm_submit
performance_cron
performance_cron_apc_prune
performance_cron_db_prune
performance_init
performance_log_details
performance_log_summary_apc
performance_log_summary_db
performance_menu
performance_nagiosImplementation of hook_nagios()
performance_nagios_infoImplementation of hook_nagios_info()
performance_settings
performance_shutdown
performance_view_details
performance_view_summary

Constants

NameDescription
PERFORMANCE_KEY

File

View source
  1. <?php
  2. // Copyright Khalid Baheyeldin 2008 of http://2bits.com
  3. define('PERFORMANCE_KEY', 'dru-perf:' . $_SERVER['HTTP_HOST'] . ':');
  4. function performance_menu($may_cache) {
  5. $items = array();
  6. if ($may_cache) {
  7. $items[] = array(
  8. 'path' => 'admin/settings/performance_logging',
  9. 'title' => t('Performance logging'),
  10. 'description' => t('Logs performance data: page generation times and memory usage.'),
  11. 'access' => user_access('access administration pages'),
  12. 'callback' => 'drupal_get_form',
  13. 'callback arguments' => array('performance_settings'),
  14. );
  15. $items[] = array(
  16. 'path' => 'admin/settings/performance_logging/apc_clear',
  17. 'title' => t('Clear APC'),
  18. 'description' => t('Clears performance statistics collected in APC.'),
  19. 'access' => user_access('access administration pages'),
  20. 'callback' => 'drupal_get_form',
  21. 'callback arguments' => array('performance_clear_apc_confirm'),
  22. );
  23. $items[] = array(
  24. 'path' => 'admin/logs/performance_logging_summary',
  25. 'title' => t('Performance Logs: Summary'),
  26. 'description' => t('View summary performance logs: page generation times and memory usage.'),
  27. 'access' => user_access('access administration pages'),
  28. 'callback' => 'performance_view_summary',
  29. );
  30. $items[] = array(
  31. 'path' => 'admin/logs/performance_logging_details',
  32. 'title' => t('Performance Logs: Details'),
  33. 'description' => t('View detailed, per page, performance logs: page generation times and memory usage.'),
  34. 'access' => user_access('access administration pages'),
  35. 'callback' => 'performance_view_details',
  36. );
  37. }
  38. return $items;
  39. }
  40. function performance_settings() {
  41. $options = array(
  42. 0 => t('Disabled'),
  43. 1 => t('Enabled'),
  44. );
  45. if (function_exists('apc_cache_info')) {
  46. drupal_set_message(t('APC is enabled. It is reasonably safe to enable summary logging on live sites.'));
  47. }
  48. else {
  49. drupal_set_message(t('APC is not enabled. It is <strong>not</strong> safe to enable summary logging to the database on live sites.'), 'error');
  50. }
  51. $form['mode'] = array(
  52. '#type' => 'fieldset',
  53. '#title' => t('Logging mode'),
  54. '#collapsible' => TRUE,
  55. );
  56. $form['mode']['performance_detail'] = array(
  57. '#type' => 'select',
  58. '#title' => t('Detailed logging'),
  59. '#default_value' => variable_get('performance_detail', 0),
  60. '#options' => $options,
  61. '#description' => t('Log memory usage and page generation times for every page. This logging mode is <strong>not</strong> suitable for large sites, as it can degrade performance severly. It is intended for use by developers, or on a test copy of the site.'),
  62. );
  63. $form['mode']['performance_summary_db'] = array(
  64. '#type' => 'select',
  65. '#title' => t('Summary logging (DB)'),
  66. '#default_value' => variable_get('performance_summary_db', 0),
  67. '#options' => $options,
  68. '#description' => t('Log summary data, such as average and maximum page generation times and memory usage to the database. This logging mode is <strong>not</strong> suitable for most live sites.'),
  69. );
  70. $disabled = TRUE;
  71. if (function_exists('apc_cache_info')) {
  72. $disabled = FALSE;
  73. }
  74. $form['mode']['performance_summary_apc'] = array(
  75. '#type' => 'select',
  76. '#title' => t('Summary logging (APC)'),
  77. '#default_value' => variable_get('performance_summary_apc', 0),
  78. '#options' => $options,
  79. '#disabled' => $disabled,
  80. '#description' => t('Log summary data, such as average and maximum page generation times and memory usage to APC, if installed. The summary will be stored in APC memory, and hence there is no load on the database. This logging to APC is suitable for most live sites, unless the number of unique page accesses is excessively high.'),
  81. );
  82. $form['other'] = array(
  83. '#type' => 'fieldset',
  84. '#title' => t('Other'),
  85. '#collapsible' => TRUE,
  86. );
  87. $form['other']['dev_query'] = array(
  88. '#type' => 'select',
  89. '#title' => t('Database Query timing and count'),
  90. '#default_value' => variable_get('dev_query', 0),
  91. '#options' => $options,
  92. '#description' => t('Log database timing and count for each page. This is useful to know if the bottleneck is in excessive database query counts, or the time required to execute those queries is high. Please note that this will automatically be enabled and disabled in the settings of the devel module. Also note that enabling this will incurr some memory overhead as query times and the actual query strings are cached in memory as arrays.'),
  93. );
  94. $form['other']['performance_threshold_accesses'] = array(
  95. '#type' => 'select',
  96. '#title' => t('Accesses threshold'),
  97. '#default_value' => variable_get('performance_threshold_accesses', 0),
  98. '#options' => array(0, 1, 2, 5, 10),
  99. '#description' => t('When displaying the summary report and using APC, only pages with the number of accesses larger than the specified threshold will be shown. Also, when cron runs, pages with that number of accesses or less will be removed, so as not to overflow APC\'s shared memory. This is useful on a live site with a high volume of hits. On a development site, you probably want this set to 0, so you can see all pages.'),
  100. );
  101. return system_settings_form($form);
  102. }
  103. function performance_init() {
  104. register_shutdown_function('performance_shutdown');
  105. }
  106. function performance_shutdown() {
  107. global $queries;
  108. if ($_GET['q']) {
  109. // q= has a value, use that for the path
  110. $path = $_GET['q'];
  111. }
  112. else {
  113. // q= is empty, use whatever the site_frontpage is set to
  114. $path = variable_get('site_frontpage', 'node');
  115. }
  116. $params = array(
  117. 'timer' => timer_read('page'),
  118. 'path' => $path,
  119. );
  120. // Memory
  121. if (function_exists('memory_get_peak_usage')) {
  122. $params['mem'] = memory_get_peak_usage(TRUE);
  123. }
  124. else {
  125. $params['mem'] = 0;
  126. }
  127. // Query time and count
  128. $query_count = 0;
  129. $query_timer = 0;
  130. if (variable_get('dev_query', 0) && is_array($queries)) {
  131. foreach ($queries as $query) {
  132. $sum += $query[1];
  133. }
  134. $query_count = count($queries);
  135. $query_timer = round($sum * 1000, 2);
  136. }
  137. $params['query_count'] = $query_count;
  138. $params['query_timer'] = $query_timer;
  139. if (variable_get('performance_detail', 0)) {
  140. performance_log_details($params);
  141. }
  142. if (variable_get('performance_summary_db', 0)) {
  143. performance_log_summary_db($params);
  144. }
  145. if (variable_get('performance_summary_apc', 0)) {
  146. if (function_exists('apc_cache_info')) {
  147. performance_log_summary_apc($params);
  148. }
  149. }
  150. }
  151. function performance_log_summary_apc($params = array()) {
  152. $key = PERFORMANCE_KEY . $params['path'];
  153. if ($data = apc_fetch($key)) {
  154. $data = array(
  155. 'path' => $data['path'],
  156. 'last_access' => time(),
  157. 'bytes_max' => max($params['mem'], $data['bytes_max']),
  158. 'bytes_avg' => ($data['bytes_avg'] + $params['mem']) / 2,
  159. 'millisecs_max' => max($params['timer'], $data['millisecs_max']),
  160. 'millisecs_avg' => ($data['millisecs_avg'] + $params['timer']) / 2,
  161. 'query_timer_max' => max($params['query_timer'], $data['query_timer_max']),
  162. 'query_timer_avg' => ($data['query_timer_avg'] + $params['query_timer']) / 2,
  163. 'query_count_max' => max($params['query_count'], $data['query_count_max']),
  164. 'query_count_avg' => ($data['query_count_avg'] + $params['query_count']) / 2,
  165. 'num_accesses' => $data['num_accesses'] + 1,
  166. );
  167. }
  168. else {
  169. $data = array(
  170. 'path' => $params['path'],
  171. 'bytes_max' => $params['mem'],
  172. 'bytes_avg' => $params['mem'],
  173. 'millisecs_max' => $params['timer'],
  174. 'millisecs_avg' => $params['timer'],
  175. 'query_timer_max' => $params['query_timer'],
  176. 'query_timer_avg' => $params['query_timer'],
  177. 'query_count_max' => $params['query_count'],
  178. 'query_count_avg' => $params['query_count'],
  179. 'num_accesses' => 1,
  180. 'last_access' => time(),
  181. );
  182. }
  183. apc_store($key, $data);
  184. }
  185. function performance_log_summary_db($params = array()) {
  186. $result = db_query("SELECT * FROM {performance_summary} WHERE path = '%s'", $params['path']);
  187. if (db_num_rows($result)) {
  188. $row = db_fetch_object($result);
  189. db_query("UPDATE {performance_summary}
  190. SET last_access = %d,
  191. num_accesses = num_accesses + 1,
  192. bytes_max = %d,
  193. bytes_avg = %d,
  194. millisecs_max = %d,
  195. millisecs_avg = %d,
  196. query_timer_max = %d,
  197. query_timer_avg = %d,
  198. query_count_max = %d,
  199. query_count_avg = %d
  200. WHERE path = '%s'",
  201. time(),
  202. max($params['mem'], $row->bytes_max),
  203. ($row->bytes_avg + $params['mem']) / 2,
  204. max($params['timer'], $row->millisecs_max),
  205. ($row->millisecs_avg + $params['timer']) / 2,
  206. max($params['query_timer'], $row->query_timer_max),
  207. ($row->query_timer_avg + $params['query_timer']) / 2,
  208. max($params['query_count'], $row->query_count_max),
  209. ($row->query_count_avg + $params['query_count']) / 2,
  210. $params['path']);
  211. }
  212. else {
  213. // First time we log this path, write fresh values
  214. db_query("INSERT INTO {performance_summary}
  215. (path, last_access, num_accesses,
  216. bytes_max, bytes_avg, millisecs_max, millisecs_avg,
  217. query_count_max, query_count_avg, query_timer_max, query_timer_avg)
  218. VALUES
  219. ('%s', %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
  220. $params['path'],
  221. time(),
  222. 1,
  223. $params['mem'],
  224. $params['mem'],
  225. $params['timer'],
  226. $params['timer'],
  227. $params['query_count'],
  228. $params['query_count'],
  229. $params['query_timer'],
  230. $params['query_timer']
  231. );
  232. }
  233. }
  234. function performance_log_details($params = array()) {
  235. global $user;
  236. $anon = ($user->uid) ? FALSE : TRUE;
  237. db_query("INSERT INTO {performance_detail} (path, anon, bytes, millisecs, timestamp, query_timer, query_count) VALUES ('%s', %d, %d, %d, %d, %d, %d)",
  238. $params['path'],
  239. $anon,
  240. $params['mem'],
  241. $params['timer'],
  242. time(),
  243. $params['query_timer'],
  244. $params['query_count']
  245. );
  246. }
  247. function performance_apc_list_all() {
  248. $key_list = array();
  249. $list = apc_cache_info('user');
  250. foreach($list['cache_list'] as $cache_id => $cache_data) {
  251. $regex = '/^' . PERFORMANCE_KEY . '/';
  252. if (preg_match($regex, $cache_data['info'])) {
  253. $key_list[] = $cache_data['info'];
  254. }
  255. }
  256. return $key_list;
  257. }
  258. function performance_view_summary() {
  259. $sum = array();
  260. $sum[] = variable_get('performance_summary_db', 0);
  261. $sum[] = variable_get('performance_summary_apc', 0);
  262. $go = array_sum($sum);
  263. if (!$go) {
  264. return t('Summary performance log is not enabled. Go to the <a href="@link">settings page</a> to enable it.', array('@link' => url('admin/settings/performance_logging')));
  265. }
  266. $header = array(
  267. array('data' => t('Path'), 'field' => 'path'),
  268. array('data' => t('Last access'), 'field' => 'last_access'),
  269. array('data' => t('# accesses'), 'field' => 'num_accesses'),
  270. array('data' => t('Max Memory (MB)'), 'field' => 'bytes_max'),
  271. array('data' => t('Avg Memory (MB)'), 'field' => 'bytes_avg'),
  272. array('data' => t('Milliseconds (Max)'), 'field' => 'millisecs_max'),
  273. array('data' => t('Milliseconds (Avg)'), 'field' => 'millisecs_avg'),
  274. array('data' => t('Query Millisecs (Max)'), 'field' => 'query_timer_max'),
  275. array('data' => t('Query Millisecs (Avg)'), 'field' => 'query_timer_avg'),
  276. array('data' => t('Query Count (Max)'), 'field' => 'query_count_max'),
  277. array('data' => t('Query Count (Avg)'), 'field' => 'query_count_avg'),
  278. );
  279. $total_rows = $shown = $last_max = $total_bytes = $total_millisecs = $total_accesses = 0;
  280. $last_min = time();
  281. $threshold = variable_get('performance_threshold_accesses', 0);
  282. if (variable_get('performance_summary_apc', 0) && function_exists('apc_cache_info')) {
  283. // Get the data from the APC cache
  284. foreach(performance_apc_list_all() as $key) {
  285. $data_list[] = apc_fetch($key);
  286. }
  287. }
  288. else {
  289. // Get the data form the database table
  290. $sql = "SELECT * FROM {performance_summary}";
  291. $tablesort = tablesort_sql($header);
  292. $result = pager_query($sql . $tablesort, 50);
  293. while($row = db_fetch_array($result)) {
  294. $data_list[] = $row;
  295. }
  296. }
  297. foreach($data_list as $data) {
  298. $total_rows++;
  299. $last_max = max($last_max, $data['last_access']);
  300. $last_min = min($last_min, $data['last_access']);
  301. // Calculate running averages
  302. $total_bytes += $data['bytes_avg'];
  303. $total_millisecs += $data['millisecs_avg'];
  304. $total_accesses += $data['num_accesses'];
  305. if ($data['num_accesses'] > $threshold) {
  306. $shown++;
  307. $rows[] = array('data' =>
  308. array(
  309. check_plain($data['path']),
  310. format_date($data['last_access'], 'small'),
  311. $data['num_accesses'],
  312. number_format($data['bytes_max']/1024/1024, 2),
  313. number_format($data['bytes_avg']/1024/1024, 2),
  314. number_format($data['millisecs_max'], 1),
  315. number_format($data['millisecs_avg'], 1),
  316. number_format($data['query_timer_max'], 1),
  317. number_format($data['query_timer_avg'], 1),
  318. $data['query_count_max'],
  319. $data['query_count_avg'],
  320. ),
  321. );
  322. }
  323. }
  324. if (!$rows) {
  325. $rows[] = array(array('data' => t('No statistics available yet.'), 'colspan' => count($header)));
  326. }
  327. if ($threshold) {
  328. $output .= t('Showing !shown paths with more than !threshold accesses, out of !total total paths.',
  329. array('!threshold' => $threshold, '!shown' => $shown, '!total' => $total_rows)) . '<br/>';
  330. }
  331. else {
  332. $output .= t('Showing all !total paths.', array('!total' => $total_rows)) . '<br/>';
  333. }
  334. // Protect against divide by zero
  335. if ($total_rows > 0) {
  336. $mb_avg = number_format($total_bytes/$total_rows/1024/1024, 1);
  337. $ms_avg = number_format($total_millisecs/$total_rows, 2);
  338. }
  339. else {
  340. $mb_avg = 'n/a';
  341. $ms_avg = 'n/a';
  342. }
  343. $output .= t('Average memory per page: !mb_avg MB', array('!mb_avg' => $mb_avg)) . '<br/>';
  344. $output .= t('Average milliseconds per page: !ms_avg', array('!ms_avg' => $ms_avg)) . '<br/>';
  345. $output .= t('Total number of page accesses: !accesses', array('!accesses' => $total_accesses)) . '<br/>';
  346. $output .= t('First access: !access.', array('!access' => format_date($last_min, 'small'))) . '<br/>';
  347. $output .= t('Last access: !access.', array('!access' => format_date($last_max, 'small'))) . '<br/>';
  348. $output .= theme('table', $header, $rows);
  349. $output .= theme('pager', NULL, 50, 0);
  350. return $output;
  351. }
  352. function performance_view_details() {
  353. if (!variable_get('performance_detail', 0)) {
  354. return t('Detail performance log is not enabled. Go to the <a href="@link">settings page</a> to enable it.', array('@link' => url('admin/settings/performance_logging')));
  355. }
  356. $header = array(
  357. array('data' => t('#'), 'field' => 'pid', 'sort' => 'desc'),
  358. array('data' => t('Date'), 'field' => 'timestamp'),
  359. array('data' => t('Path'), 'field' => 'path'),
  360. array('data' => t('Memory (MB)'), 'field' => 'bytes'),
  361. array('data' => t('Milliseconds (Total)'), 'field' => 'millisecs'),
  362. array('data' => t('Anonymous?'), 'field' => 'anon'),
  363. array('data' => t('# Queries'), 'field' => 'query_count'),
  364. array('data' => t('Query Milliseconds'), 'field' => 'query_timer'),
  365. );
  366. $sql = "SELECT * FROM {performance_detail}";
  367. $tablesort = tablesort_sql($header);
  368. $result = pager_query($sql . $tablesort, 50);
  369. while ($data = db_fetch_array($result)) {
  370. $rows[] = array('data' =>
  371. array(
  372. $data['pid'],
  373. format_date($data['timestamp'], 'small'),
  374. check_plain($data['path']),
  375. number_format($data['bytes']/1024/1024, 2),
  376. $data['millisecs'],
  377. ($data['anon']) ? t('Yes') : t('No'),
  378. $data['query_count'],
  379. $data['query_timer'],
  380. ),
  381. );
  382. }
  383. if (!$rows) {
  384. $rows[] = array(array('data' => t('No log messages available.'), 'colspan' => count($header)));
  385. }
  386. $output .= theme('table', $header, $rows);
  387. $output .= theme('pager', NULL, 50, 0);
  388. return $output;
  389. }
  390. function performance_cron() {
  391. // One day ago ...
  392. $timestamp = time() - 24*60*60;
  393. performance_cron_db_prune($timestamp);
  394. performance_cron_apc_prune($timestamp);
  395. }
  396. function performance_cron_db_prune($timestamp = 0) {
  397. // Remove rows which have not been accessed since a certain timestamp
  398. db_query("DELETE FROM {performance_summary} WHERE last_access <= %d", $timestamp);
  399. }
  400. function performance_cron_apc_prune($timestamp = 0) {
  401. if (!function_exists('apc_cache_info')) {
  402. // APC not enabled, nothing to do ...
  403. return;
  404. }
  405. // Get all entries in APC's user cache
  406. $list = performance_apc_list_all();
  407. if (!count($list)) {
  408. // Nothing stored yet
  409. return;
  410. }
  411. foreach($list as $key) {
  412. if ($data = apc_fetch($key)) {
  413. if ($data['last_access'] <= $timestamp) {
  414. apc_delete($key);
  415. }
  416. }
  417. }
  418. }
  419. function performance_clear_apc_confirm() {
  420. $form['confirm'] = array(
  421. '#value' => t('Confirm APC clear'),
  422. );
  423. return confirm_form(
  424. $form,
  425. t('Are you sure you want to clear the APC statistics for this site?'),
  426. 'admin/settings/performance_logging',
  427. t('This will clear all the collected performance statistics stored in APC. This action cannot be undone.'),
  428. t('Clear'),
  429. t('Cancel'));
  430. }
  431. function performance_clear_apc_confirm_submit($form_id, &$form) {
  432. if (!function_exists('apc_cache_info')) {
  433. drupal_set_message(t('APC is not enabled. Nothing to do ...'));
  434. drupal_goto('admin/settings/performance');
  435. return;
  436. }
  437. $list = performance_apc_list_all();
  438. if (!count($list)) {
  439. // Nothing stored yet
  440. return;
  441. }
  442. foreach($list as $key) {
  443. if ($data = apc_fetch($key)) {
  444. apc_delete($key);
  445. }
  446. }
  447. drupal_set_message(t('Performance statistics collected in APC has been cleared.'));
  448. drupal_goto('admin/settings/performance');
  449. }
  450. /**
  451. * Implementation of hook_nagios_info()
  452. */
  453. function performance_nagios_info() {
  454. return array(
  455. 'name' => 'Performance logging',
  456. 'id' => 'PERF',
  457. );
  458. }
  459. /**
  460. * Implementation of hook_nagios()
  461. */
  462. function performance_nagios() {
  463. $info = performance_nagios_info();
  464. $id = $info['id'];
  465. // Find out if we have what we need enabled
  466. $sum = array();
  467. $sum[] = variable_get('performance_summary_db', 0);
  468. $sum[] = variable_get('performance_summary_apc', 0);
  469. $go = array_sum($sum);
  470. if (!$go) {
  471. return array(
  472. $id => array(
  473. 'status' => NAGIOS_STATUS_UNKNOWN,
  474. 'type' => 'perf',
  475. 'text' => t('Performance logging is not enabled'),
  476. ),
  477. );
  478. }
  479. // Initialize variables
  480. $total_rows = $total_bytes = $total_millisecs = $total_accesses = $total_query_time = $total_query_count = 0;
  481. // Check which data store to use
  482. if (variable_get('performance_summary_apc', 0) && function_exists('apc_cache_info')) {
  483. // Get the data from the APC cache
  484. foreach(performance_apc_list_all() as $key) {
  485. $data_list[] = apc_fetch($key);
  486. }
  487. }
  488. else {
  489. // Get the data form the database table for URLs that have been accessed in the last 15 minutes
  490. $result = db_query("SELECT * FROM {performance_summary} WHERE last_access >= %d", time() - 15*60);
  491. while($row = db_fetch_array($result)) {
  492. $data_list[] = $row;
  493. }
  494. }
  495. foreach($data_list as $data) {
  496. $total_rows++;
  497. // Calculate running averages
  498. $total_bytes += $data['bytes_avg'];
  499. $total_millisecs += $data['millisecs_avg'];
  500. $total_accesses += $data['num_accesses'];
  501. $total_query_time += $data['query_timer_avg'];
  502. $total_query_count += $data['query_count_avg'];
  503. }
  504. // Protect against divide by zero
  505. if ($total_rows > 0) {
  506. $ms_avg = number_format($total_millisecs / $total_rows, 1, '.', '');
  507. $ms_query = number_format($total_query_time / $total_rows, 1, '.', '');
  508. $query_count = number_format($total_query_count / $total_rows, 2, '.', '');
  509. $mb_avg = number_format($total_bytes / $total_rows/1024/1024, 1);
  510. }
  511. else {
  512. $mb_avg = '';
  513. $ms_avg = '';
  514. $ms_query = '';
  515. $query_count = '';
  516. }
  517. $status = NAGIOS_STATUS_OK;
  518. return array(
  519. 'ACC' => array(
  520. 'status' => $status,
  521. 'type' => 'perf',
  522. 'text' => $total_accesses,
  523. ),
  524. 'MS' => array(
  525. 'status' => $status,
  526. 'type' => 'perf',
  527. 'text' => $ms_avg,
  528. ),
  529. 'MMB' => array(
  530. 'status' => $status,
  531. 'type' => 'perf',
  532. 'text' => $mb_avg,
  533. ),
  534. 'QRC' => array(
  535. 'status' => $status,
  536. 'type' => 'perf',
  537. 'text' => $query_count,
  538. ),
  539. 'QRT' => array(
  540. 'status' => $status,
  541. 'type' => 'perf',
  542. 'text' => $ms_query,
  543. ),
  544. );
  545. }