performance.module 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. <?php
  2. /**
  3. * @file
  4. *
  5. * Logs detailed and/or summary page generation time and memory consumption for
  6. * page requests.
  7. * Copyright Khalid Baheyeldin 2008 of http://2bits.com
  8. */
  9. // Check for a variable for the performance key. This allows you to set a
  10. // unique key in the case that you have multiple domains accessing the same
  11. // site. If this is not set, fall back to the hostname which we get from the
  12. // base_url global variable for drush compatibility (you will need to pass the
  13. // --url parameter to drush).
  14. define('PERFORMANCE_KEY', 'dru-perf:' . variable_get('performance_key', parse_url($GLOBALS['base_url'], PHP_URL_HOST)) . ':');
  15. define('PERFORMANCE_BIN', 'cache_performance');
  16. define('PERFORMANCE_QUERY_VAR', 'performance_query');
  17. define('PERFORMANCE_CACHE', 'cache_default_class');
  18. define('PERFORMANCE_SETTINGS', 'admin/config/development/performance-logging');
  19. include_once variable_get('performance_detail_logging', 'includes/performance.details.inc');
  20. /**
  21. * Implements hook_menu().
  22. */
  23. function performance_menu() {
  24. $items = array();
  25. $items[PERFORMANCE_SETTINGS] = array(
  26. 'title' => 'Performance logging',
  27. 'description' => 'Logs performance data: page generation times and memory usage.',
  28. 'page callback' => 'drupal_get_form',
  29. 'page arguments' => array('performance_settings_form'),
  30. 'access arguments' => array('administer performance logging'),
  31. 'type' => MENU_NORMAL_ITEM,
  32. );
  33. $items['admin/reports/performance-logging'] = array(
  34. 'title' => 'Performance logs',
  35. 'description' => 'View summary performance logs: page generation times and memory usage.',
  36. 'page callback' => 'performance_view_summary',
  37. 'access arguments' => array('administer performance logging'),
  38. 'type' => MENU_NORMAL_ITEM,
  39. );
  40. $items['admin/reports/performance-logging/summary'] = array(
  41. 'title' => 'Summary',
  42. 'type' => MENU_DEFAULT_LOCAL_TASK,
  43. 'weight' => 0,
  44. );
  45. $items['admin/reports/performance-logging/details'] = array(
  46. 'title' => 'Details',
  47. 'description' => 'View detailed, per page, performance logs: page generation times and memory usage.',
  48. 'page callback' => 'performance_view_details',
  49. 'access arguments' => array('administer performance logging'),
  50. 'type' => MENU_LOCAL_TASK,
  51. 'weight' => 1,
  52. );
  53. // We use no % after clear here (clear/%) to catch the arguments because we do
  54. // not want the clear page to fall back on its parent when no argument is
  55. // passed. See the callback of the page for more info.
  56. $items['admin/reports/performance-logging/clear'] = array(
  57. 'title' => 'Clear logs',
  58. 'description' => 'Clears all collected performance statistics.',
  59. 'page callback' => 'drupal_get_form',
  60. 'page arguments' => array('performance_clear_form'),
  61. 'access arguments' => array('administer performance logging'),
  62. 'type' => MENU_CALLBACK,
  63. 'weight' => 1,
  64. );
  65. return $items;
  66. }
  67. /**
  68. * Implements hook_permission().
  69. */
  70. function performance_permission() {
  71. return array(
  72. 'administer performance logging' => array(
  73. 'title' => t('Administer performance logging'),
  74. 'description' => t('Allows both configuring the performance module and accessing its reports.'),
  75. )
  76. );
  77. }
  78. /**
  79. * Implements hook_cron().
  80. */
  81. function performance_cron() {
  82. // Remove all entries that have expired.
  83. // TODO: make this work as expected, seems to throw away everything now :-s
  84. cache_clear_all(NULL, PERFORMANCE_BIN);
  85. // Remove entries that have less than so many accesses
  86. performance_traverse_cache('performance_cron_prune');
  87. // Remove performance_detail rows on a daily basis.
  88. if (variable_get('performance_detail', 0)) {
  89. performance_prune_details();
  90. }
  91. }
  92. /**
  93. * Callback used by performance_traverse_cache() for pruning data on cron based
  94. * on a preset threshold.
  95. *
  96. * @param $cache cache object
  97. *
  98. * @see performance_traverse_cache()
  99. */
  100. function performance_cron_prune($cache) {
  101. static $threshold;
  102. // Prevent a variable_get() each time this callback is triggered.
  103. if(!isset($threshold)) {
  104. $threshold = variable_get('performance_threshold_accesses', 0);
  105. }
  106. if ($threshold && $cache->data['num_accesses'] <= $threshold) {
  107. cache_clear_all($cache->cid, PERFORMANCE_BIN);
  108. }
  109. return;
  110. }
  111. /**
  112. * Implements hook_views_api().
  113. */
  114. function performance_views_api() {
  115. return array(
  116. 'api' => 3,
  117. 'path' => drupal_get_path('module', 'performance') . '/includes',
  118. );
  119. }
  120. /**
  121. * System settings form.
  122. */
  123. function performance_settings_form() {
  124. $status = performance_caching_message();
  125. // Setup settings form.
  126. $form['mode'] = array(
  127. '#type' => 'fieldset',
  128. '#title' => t('Logging mode'),
  129. '#collapsible' => TRUE,
  130. );
  131. $form['mode']['performance_detail'] = array(
  132. '#type' => 'checkbox',
  133. '#title' => t('Detailed logging'),
  134. '#default_value' => variable_get('performance_detail', 0),
  135. '#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.'),
  136. );
  137. $form['mode']['performance_summary'] = array(
  138. '#type' => 'checkbox',
  139. '#title' => t('Summary logging'),
  140. '#default_value' => variable_get('performance_summary', 0),
  141. '#description' => t('Log summary data, such as average and maximum page generation times and memory usage.'),
  142. );
  143. if ($status != 'error') {
  144. $form['mode']['performance_summary']['#description'] .= ' ' . t('The summary will be stored in an alternative cache, and hence there is no load on the database. This logging is suitable for most live sites, unless the number of unique page accesses is excessively high.');
  145. }
  146. else {
  147. $form['mode']['performance_summary']['#description'] .= ' ' . t('This logging mode is <strong>not</strong> suitable for most live sites.');
  148. }
  149. $form['other'] = array(
  150. '#type' => 'fieldset',
  151. '#title' => t('Other'),
  152. '#collapsible' => TRUE,
  153. );
  154. $form['other'][PERFORMANCE_QUERY_VAR] = array(
  155. '#type' => 'checkbox',
  156. '#title' => t('Database Query timing and count'),
  157. '#default_value' => variable_get(PERFORMANCE_QUERY_VAR, 0),
  158. '#description' => t('Log database query timing and query 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. Enabling this will incurr some memory overhead as query times and the actual query strings are cached in memory as arrays for each page, hence skewing the overall page memory reported.'),
  159. );
  160. $form['other']['performance_threshold_accesses'] = array(
  161. '#type' => 'select',
  162. '#title' => t('Accesses threshold'),
  163. '#default_value' => variable_get('performance_threshold_accesses', 0),
  164. '#options' => array(0, 1, 2, 5, 10),
  165. '#description' => t("When displaying the summary report, only pages with the number of accesses larger than the specified threshold will be shown. Also, when cron runs and summary is <strong>not</strong> logged to DB, pages with that number of accesses or less will be removed, so as not to overflow the cache's 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."),
  166. );
  167. $form['other']['performance_nodrush'] = array(
  168. '#type' => 'checkbox',
  169. '#title' => t('Do not log drush access'),
  170. '#default_value' => variable_get('performance_nodrush', 1),
  171. '#description' => t('Prevent !link access to the site from being logged.', array('!link' => l(t('drush'), 'http://www.drupal.org/project/drush', array('attributes' => array('target' => '_blank'))))),
  172. );
  173. $form['other']['performance_skip_paths'] = array(
  174. '#type' => 'textarea',
  175. '#title' => t('Paths to exclude'),
  176. '#default_value' => variable_get('performance_skip_paths', ''),
  177. '#description' => t("Enter one path per line as Drupal paths. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>')),
  178. );
  179. return system_settings_form($form);
  180. }
  181. /**
  182. * Display message on settings form.
  183. */
  184. function performance_caching_message() {
  185. $default = 'DrupalDatabaseCache';
  186. $type = 'error';
  187. $cache = variable_get(PERFORMANCE_CACHE, $default);
  188. if ($cache != $default) {
  189. $message = t('Alternative caching (%class) is enabled. It is reasonably safe to enable summary logging on live sites.', array('%class' => $cache));
  190. $type = 'status';
  191. }
  192. else {
  193. $message = t('Only the default database caching mechanism is enabled. It is <strong>not</strong> safe to enable summary logging to the database on live sites!');
  194. }
  195. drupal_set_message($message, $type, FALSE);
  196. return $type;
  197. }
  198. /**
  199. * Implements hook_boot().
  200. */
  201. function performance_boot() {
  202. register_shutdown_function('performance_shutdown');
  203. if (variable_get(PERFORMANCE_QUERY_VAR, 0)) {
  204. @include_once DRUPAL_ROOT . '/includes/database/log.inc';
  205. Database::startLog('performance', 'default');
  206. }
  207. }
  208. /**
  209. * Shutdown function that collects all performance data.
  210. */
  211. function performance_shutdown() {
  212. global $user, $language;
  213. // Don't log drush access.
  214. if (drupal_is_cli() && variable_get('performance_nodrush', 1)) {
  215. return;
  216. }
  217. if (isset($_GET['q']) && $_GET['q']) {
  218. // q= has a value, use that for the path
  219. $path = $_GET['q'];
  220. }
  221. elseif (drupal_is_cli()) {
  222. $path = 'drush';
  223. }
  224. else {
  225. // q= is empty, use whatever the site_frontpage is set to
  226. $path = variable_get('site_frontpage', 'node');
  227. }
  228. // Skip if page from cache or on certain paths defined by the user.
  229. if (!function_exists('drupal_match_path') || drupal_match_path($path, variable_get('performance_skip_paths', ''))) {
  230. return;
  231. }
  232. $params = array(
  233. 'timer' => timer_read('page'),
  234. 'path' => $path,
  235. );
  236. // Memory.
  237. // No need to check if this function exists in D7, as it has a minimal
  238. // requirement of PHP 5.2.5.
  239. $params['mem'] = memory_get_peak_usage(TRUE);
  240. // Query time and count
  241. $query_count = $query_timer = $sum = 0;
  242. if (variable_get(PERFORMANCE_QUERY_VAR, 0)) {
  243. // See http://drupal.org/node/1022204
  244. $queries = Database::getLog('performance', 'default');
  245. foreach ($queries as $query) {
  246. $sum += $query['time'];
  247. $query_count++;
  248. }
  249. $query_timer = round($sum * 1000, 2);
  250. }
  251. $params['query_count'] = $query_count;
  252. $params['query_timer'] = $query_timer;
  253. // Anonymous access?
  254. $params['anon'] = ($user->uid) ? 0 : 1;
  255. // Language
  256. $params['language'] = $language->language;
  257. // There used to be a module_invoke_all('performance', 'header', $header) call
  258. // here but it has been removed. $header was an associative array containing
  259. // path, timer (ms) and anon ('Yes' or 'No').
  260. if (variable_get('performance_detail', 0)) {
  261. // There used to be a module_invoke_all('performance', 'data') call here. As
  262. // it was undocumented and therefore unknown, it has been removed. The data
  263. // column has been kept so that we can re-implement if needed.
  264. $params['data'] = NULL;
  265. performance_log_details($params);
  266. }
  267. // There used to be a module_invoke_all('performance', 'disable') call here in
  268. // an else statement.
  269. if (variable_get('performance_summary', 0)) {
  270. performance_log_summary($params);
  271. }
  272. }
  273. /**
  274. * Store the summary data.
  275. */
  276. function performance_log_summary($params) {
  277. $key = PERFORMANCE_KEY . $params['path'] . ':' . $params['language'] . ':' . $params['anon'];
  278. $data = cache_get($key, PERFORMANCE_BIN);
  279. if (is_object($data)) {
  280. $data = $data->data;
  281. }
  282. $result = performance_build_summary_data($data, $params);
  283. if ($result['type'] == 'new') {
  284. // $keys_cache is used to easily retrieve our data later on.
  285. if ($keys_cache = cache_get(PERFORMANCE_KEY, PERFORMANCE_BIN)) {
  286. $keys_values = $keys_cache->data;
  287. }
  288. // Keep the key for the key cache store. We do it this way so that keys
  289. // will replace eachother which would not happen when using
  290. // $keys_values[] = $key;
  291. $keys_values[$key] = 1;
  292. cache_set(PERFORMANCE_KEY, $keys_values, PERFORMANCE_BIN);
  293. }
  294. // Keep records for 1 day.
  295. $expire = $result['data']['last_access'] + (24 * 60 * 60);
  296. cache_set($key, $result['data'], PERFORMANCE_BIN, $expire);
  297. }
  298. /**
  299. * Helper function to build summary data array.
  300. *
  301. * @param data array of previous data
  302. * @param params array of current data
  303. * @return array holding summary data
  304. */
  305. function performance_build_summary_data($data, $params) {
  306. if ($data) {
  307. $type = 'existing';
  308. $data = array(
  309. 'path' => $data['path'],
  310. 'bytes_max' => max($params['mem'], $data['bytes_max']),
  311. 'bytes_sum' => $data['bytes_sum'] + $params['mem'],
  312. 'ms_max' => max($params['timer'], $data['ms_max']),
  313. 'ms_sum' => $data['ms_sum'] + $params['timer'],
  314. 'query_timer_max' => max($params['query_timer'], $data['query_timer_max']),
  315. 'query_timer_sum' => $data['query_timer_sum'] + $params['query_timer'],
  316. 'query_count_max' => max($params['query_count'], $data['query_count_max']),
  317. 'query_count_sum' => $data['query_count_sum'] + $params['query_count'],
  318. 'num_accesses' => $data['num_accesses'] + 1,
  319. 'last_access' => REQUEST_TIME,
  320. 'anon' => $params['anon'],
  321. 'language' => $params['language'],
  322. );
  323. }
  324. else {
  325. $type = 'new';
  326. $data = array(
  327. 'path' => $params['path'],
  328. 'bytes_max' => $params['mem'],
  329. 'bytes_sum' => $params['mem'],
  330. 'ms_max' => (int)$params['timer'],
  331. 'ms_sum' => (int)$params['timer'],
  332. 'query_timer_max' => $params['query_timer'],
  333. 'query_timer_sum' => $params['query_timer'],
  334. 'query_count_max' => (int)$params['query_count'],
  335. 'query_count_sum' => (int)$params['query_count'],
  336. 'num_accesses' => 1,
  337. 'last_access' => REQUEST_TIME,
  338. 'anon' => $params['anon'],
  339. 'language' => $params['language'],
  340. );
  341. }
  342. return array('data' => $data, 'type' => $type);
  343. }
  344. /**
  345. * Helper function to traverse the cache_bin data for retrieving and/or
  346. * pruning data.
  347. *
  348. * @param $callback string function to execute on the data fetched
  349. * @param $args optional additional argument(s) to pass to the callback (use an
  350. * array or object to pass multiple arguments)
  351. * @return array of data where the contents depends on the callback
  352. */
  353. function performance_traverse_cache($callback, $args = NULL) {
  354. $data_list = array();
  355. $pruned = FALSE;
  356. if ($keys_cache = cache_get(PERFORMANCE_KEY, PERFORMANCE_BIN)) {
  357. // is_array() check to prevent anything from ever going wrong here.
  358. if (is_array($keys_cache->data)) {
  359. foreach ($keys_cache->data as $key => $value) {
  360. $cache = cache_get($key, PERFORMANCE_BIN);
  361. if (!$cache) {
  362. // Cache entry for this key has expired, remove the key.
  363. unset($keys_cache->data[$key]);
  364. // Mark as pruned: we have to rewrite the keys cache!
  365. $pruned = TRUE;
  366. }
  367. else {
  368. // call_user_func() does not support passing by reference. See
  369. // http://php.net/manual/en/function.call-user-func-array.php and the
  370. // note about PHP 5.4 concerning the possibility of passing by
  371. // reference there. Hence this approach to prevent future
  372. // compatibility issues
  373. if ($data = call_user_func($callback, $cache, $args)) {
  374. $data_list[] = $data;
  375. }
  376. }
  377. }
  378. }
  379. }
  380. // Write the pruned key cache if needed.
  381. if ($pruned) {
  382. cache_set(PERFORMANCE_KEY, $keys_cache->data, PERFORMANCE_BIN);
  383. }
  384. return $data_list;
  385. }
  386. /**
  387. * Callback used by performance_traverse_cache() for fetching summary data.
  388. *
  389. * @param $cache cache object
  390. * @param $timestamp unix timestamp to start fetching data from
  391. * @return the processed data or NULL
  392. *
  393. * @see performance_traverse_cache()
  394. */
  395. function performance_get_summary($cache, $timestamp) {
  396. static $count = 0;
  397. // Don't combine these IF statemens here, otherwise else might get executed
  398. // while $timestamp IS set!
  399. if ($timestamp !== NULL) {
  400. if($cache->created >= $timestamp) {
  401. // return based on timestamp
  402. return $cache->data;
  403. }
  404. }
  405. else {
  406. // return paged
  407. global
  408. $pager_page_array, // array of element-keyed current page - 1
  409. $pager_total_items, // array of element-keyed total number of data rows
  410. $pager_limits, // array of element-keyed number of rows per page
  411. $pager_total; // array of element-keyed total number of pages
  412. $pager_total_items[0]++;
  413. if (($pager_page_array[0] * $pager_limits[0]) < $pager_total_items[0] && $count < $pager_limits[0]) {
  414. $count++;
  415. return $cache->data;
  416. }
  417. }
  418. return;
  419. }
  420. /**
  421. * Summary page callback.
  422. */
  423. function performance_view_summary() {
  424. drupal_set_title(t('Performance logs: Summary'));
  425. global
  426. $pager_page_array, // array of element-keyed current page - 1
  427. $pager_total_items, // array of element-keyed total number of data rows
  428. $pager_limits, // array of element-keyed number of rows per page
  429. $pager_total; // array of element-keyed total number of pages
  430. $rows = $data_list = array();
  431. // Build table header.
  432. $header = array(
  433. array('data' => t('Path'), 'field' => 'path'),
  434. array('data' => t('Last access'), 'field' => 'last_access'),
  435. array('data' => t('# accesses'), 'field' => 'num_accesses'),
  436. array('data' => t('MB Memory (Max)'), 'field' => 'bytes_max'),
  437. array('data' => t('MB Memory (Avg)'), 'field' => 'bytes_sum'),
  438. array('data' => t('ms (Max)'), 'field' => 'ms_max'),
  439. array('data' => t('ms (Avg)'), 'field' => 'ms_sum'),
  440. array('data' => t('Language'), 'field' => 'language'),
  441. array('data' => t('Anonymous?'), 'field' => 'anon'),
  442. );
  443. if (variable_get(PERFORMANCE_QUERY_VAR, 0)) {
  444. $header[] = array('data' => t('Query ms (Max)'), 'field' => 'query_timer_max');
  445. $header[] = array('data' => t('Query ms (Avg)'), 'field' => 'query_timer_sum');
  446. $header[] = array('data' => t('Query Count (Max)'), 'field' => 'query_count_max');
  447. $header[] = array('data' => t('Query Count (Avg)'), 'field' => 'query_count_sum');
  448. }
  449. // Set up pager since this is not done automatically when using caching bins.
  450. // Note that there can be data in these variables already hence the 'keyed'
  451. // setup of the arrays.
  452. $pager_height = 50;
  453. $pager_total_items = array(0 => 0);
  454. $pager_limits = array(0 => $pager_height);
  455. $page = isset($_GET['page']) ? sprintf('%d', $_GET['page']) : 0;
  456. $pager_page_array = array(0 => $page);
  457. $data_list = performance_traverse_cache('performance_get_summary');
  458. if (empty($data_list) && !variable_get('performance_summary', 0)) {
  459. return t('Summary performance log is not enabled. Go to the !link to enable it.', array('!link' => l(t('settings page'), PERFORMANCE_SETTINGS, array('query' => drupal_get_destination())))
  460. );
  461. }
  462. elseif (!variable_get('performance_summary', 0)) {
  463. drupal_set_message(t('Summary performance log is not enabled! Showing stored logs.'), 'warning');
  464. }
  465. $pager_total = array(0 => ceil($pager_total_items[0] / $pager_limits[0]));
  466. // Setup sorting since this is not done automatically when using caching bins.
  467. $sort_direction = tablesort_get_sort($header);
  468. $sort_field = tablesort_get_order($header);
  469. // TODO: find a solution for the avg columns! These need to be calculated
  470. // first, prolly...
  471. $data_list = performance_sort_summary($data_list, $sort_direction, $sort_field['sql']);
  472. // Format data into table.
  473. $threshold = variable_get('performance_threshold_accesses', 0);
  474. $total_rows = $shown = $last_max = $total_bytes = $total_ms = $total_accesses = 0;
  475. $last_min = REQUEST_TIME;
  476. foreach ($data_list as $data) {
  477. $total_rows++;
  478. $last_max = max($last_max, $data['last_access']);
  479. $last_min = min($last_min, $data['last_access']);
  480. // Calculate running averages.
  481. $total_bytes += $data['bytes_sum'] / $data['num_accesses'];
  482. $total_ms += $data['ms_sum'] / $data['num_accesses'];
  483. $total_accesses += $data['num_accesses'];
  484. $row_data = array();
  485. if ($data['num_accesses'] > $threshold) {
  486. $shown++;
  487. $row_data[] = l($data['path'], $data['path']);
  488. $row_data[] = format_date($data['last_access'], 'small');
  489. $row_data[] = $data['num_accesses'];
  490. $row_data[] = number_format($data['bytes_max'] / 1024 / 1024, 2);
  491. $row_data[] = number_format($data['bytes_sum'] / $data['num_accesses'] / 1024 / 1024, 2);
  492. $row_data[] = number_format($data['ms_max'], 1);
  493. $row_data[] = number_format($data['ms_sum'] / $data['num_accesses'], 1);
  494. $row_data[] = $data['language'];
  495. $row_data[] = ($data['anon']) ? t('Yes') : t('No');
  496. if (variable_get(PERFORMANCE_QUERY_VAR, 0)) {
  497. $row_data[] = number_format($data['query_timer_max'], 1);
  498. $row_data[] = number_format($data['query_timer_sum'] / $data['num_accesses'], 1);
  499. $row_data[] = $data['query_count_max'];
  500. $row_data[] = $data['query_count_sum'] / $data['num_accesses'];
  501. }
  502. }
  503. $rows[] = array('data' => $row_data);
  504. }
  505. $output = '';
  506. if ($threshold) {
  507. $output .= t('Showing !shown paths with more than !threshold accesses, out of !total total paths.',
  508. array('!threshold' => $threshold, '!shown' => $shown, '!total' => $total_rows)) . '<br/>';
  509. }
  510. else {
  511. $output .= t('Showing all !total paths.', array('!total' => $total_rows)) . '<br/>';
  512. }
  513. // Protect against divide by zero.
  514. if ($total_rows > 0) {
  515. $mb_avg = number_format($total_bytes / $total_rows / 1024 / 1024, 1);
  516. $ms_avg = number_format($total_ms / $total_rows, 2);
  517. }
  518. else {
  519. $mb_avg = 'n/a';
  520. $ms_avg = 'n/a';
  521. }
  522. $output .= t('Average memory per page: !mb_avg MB', array('!mb_avg' => $mb_avg)) . '<br/>';
  523. $output .= t('Average duration per page: !ms_avg ms', array('!ms_avg' => $ms_avg)) . '<br/>';
  524. $output .= t('Total number of page accesses: !accesses', array('!accesses' => $total_accesses)) . '<br/>';
  525. $output .= t('First access: !access.', array('!access' => format_date($last_min, 'small'))) . '<br/>';
  526. $output .= t('Last access: !access.', array('!access' => format_date($last_max, 'small')));
  527. // Return a renderable array.
  528. return array(
  529. 'general_info' => array(
  530. '#prefix' => '<p>',
  531. '#markup' => $output,
  532. '#suffix' => '</p><p>&nbsp;</p>',
  533. ),
  534. 'query_data_summary' => array(
  535. '#theme' => 'table',
  536. '#header' => $header,
  537. '#rows' => $rows,
  538. '#sticky' => TRUE,
  539. '#empty' => t('No statistics available yet.'),
  540. ),
  541. 'pager' => array(
  542. '#theme' => 'pager',
  543. '#quantity' => $pager_height,
  544. ),
  545. 'clear' => array(
  546. '#markup' => l(t('Clear logs'), 'admin/reports/performance-logging/clear/summary'),
  547. ),
  548. );
  549. }
  550. /**
  551. * Helper function to sort data from the cache bin.
  552. *
  553. * @param $data array of data to sort
  554. * @param $direction string asc or desc
  555. * @param $field string name of field to sort
  556. * @return sorted $data array
  557. *
  558. * @see array_multisort()
  559. */
  560. function performance_sort_summary($data, $direction, $field) {
  561. if(empty($data)) {
  562. return $data;
  563. }
  564. switch($direction) {
  565. case 'asc':
  566. $direction = SORT_ASC;
  567. break;
  568. case 'desc':
  569. $direction = SORT_DESC;
  570. break;
  571. }
  572. // Extract the column of data to be sorted.
  573. $column = array();
  574. foreach ($data as $key => $row) {
  575. $column[$key] = $row[$field];
  576. }
  577. array_multisort($column, $direction, $data);
  578. return $data;
  579. }
  580. /**
  581. * Clear logs form.
  582. */
  583. function performance_clear_form($form, &$form_state, $store = NULL) {
  584. $base = 'admin/reports/performance-logging/';
  585. // Seemed the best solution, instead of doing something like
  586. // t('Are you sure you want to clear all @store data?', array ('@store' => $store));
  587. switch ($store) {
  588. case 'summary':
  589. $question = t('Are you sure you want to clear all summary data?');
  590. $path = $base . 'summary';
  591. break;
  592. case 'details':
  593. $question = t('Are you sure you want to clear all detail data?');
  594. $path = $base . 'details';
  595. break;
  596. default:
  597. // None or unrecognised store => 404.
  598. drupal_not_found();
  599. return 2;
  600. }
  601. $form['store'] = array(
  602. '#type' => 'value',
  603. '#value' => $store,
  604. );
  605. $form['redirect'] = array(
  606. '#type' => 'value',
  607. '#value' => $path,
  608. );
  609. return confirm_form($form, $question, $path);
  610. }
  611. /**
  612. * Clear logs form submit handler.
  613. */
  614. function performance_clear_form_submit($form, &$form_state) {
  615. switch ($form_state['values']['store']) {
  616. case 'summary':
  617. cache_clear_all('*', PERFORMANCE_BIN, TRUE);
  618. break;
  619. case 'details':
  620. performance_clear_details();
  621. break;
  622. }
  623. $form_state['redirect'] = array($form_state['values']['redirect']);
  624. }
  625. /**
  626. * Gather performance data for external modules.
  627. */
  628. function performance_gather_summary_data() {
  629. // Data from last 15 minutes.
  630. $timestamp = REQUEST_TIME - 15 * 60;
  631. $data_list = performance_traverse_cache('performance_get_summary', $timestamp);
  632. // Initialize variables.
  633. $total_rows = $total_bytes = $total_ms = $total_accesses = $total_query_time = $total_query_count = 0;
  634. foreach ($data_list as $data) {
  635. $total_rows++;
  636. // Calculate running averages.
  637. $total_bytes += $data['bytes_sum'] / $data['num_accesses'];
  638. $total_ms += $data['ms_sum'] / $data['num_accesses'];
  639. $total_accesses += $data['num_accesses'];
  640. $total_query_time += $data['query_timer_sum'] / $data['num_accesses'];
  641. $total_query_count += $data['query_count_sum'] / $data['num_accesses'];
  642. }
  643. $results = array();
  644. $results['total_accesses'] = $total_accesses;
  645. // Protect against divide by zero.
  646. if ($total_rows > 0) {
  647. $results['ms_avg'] = number_format($total_ms / $total_rows, 1, '.', '');
  648. $results['ms_query'] = number_format($total_query_time / $total_rows, 1, '.', '');
  649. $results['query_count'] = number_format($total_query_count / $total_rows, 2, '.', '');
  650. $results['mb_avg'] = number_format($total_bytes / $total_rows / 1024 / 1024, 1);
  651. }
  652. else {
  653. $results['ms_avg'] = '';
  654. $results['ms_query'] = '';
  655. $results['mb_avg'] = '';
  656. $results['query_count'] = '';
  657. }
  658. return $results;
  659. }
  660. /**
  661. * Implements hook_nagios_info().
  662. */
  663. function performance_nagios_info() {
  664. return array(
  665. 'name' => 'Performance logging',
  666. 'id' => 'PERF',
  667. );
  668. }
  669. /**
  670. * Implements hook_nagios().
  671. */
  672. function performance_nagios() {
  673. $data = performance_gather_summary_data();
  674. if (!$data) {
  675. $info = performance_nagios_info();
  676. return array(
  677. $info['id'] => array(
  678. 'status' => NAGIOS_STATUS_UNKNOWN,
  679. 'type' => 'perf',
  680. 'text' => t('Performance logging is not enabled'),
  681. ),
  682. );
  683. }
  684. $status = NAGIOS_STATUS_OK;
  685. return array(
  686. 'ACC' => array(
  687. 'status' => $status,
  688. 'type' => 'perf',
  689. 'text' => $data['total_accesses'],
  690. ),
  691. 'MS' => array(
  692. 'status' => $status,
  693. 'type' => 'perf',
  694. 'text' => $data['ms_avg'],
  695. ),
  696. 'MMB' => array(
  697. 'status' => $status,
  698. 'type' => 'perf',
  699. 'text' => $data['mb_avg'],
  700. ),
  701. 'QRC' => array(
  702. 'status' => $status,
  703. 'type' => 'perf',
  704. 'text' => $data['query_count'],
  705. ),
  706. 'QRT' => array(
  707. 'status' => $status,
  708. 'type' => 'perf',
  709. 'text' => $data['ms_query'],
  710. ),
  711. );
  712. }
  713. /**
  714. * Implements hook_prod_check_alter().
  715. */
  716. function performance_prod_check_alter(&$checks) {
  717. $checks['perf_data']['functions']['performance_prod_check_return_data'] = 'Performance logging';
  718. }
  719. /**
  720. * Return performance data to Production Monitor.
  721. */
  722. function performance_prod_check_return_data() {
  723. $data = performance_gather_summary_data();
  724. if (!$data) {
  725. return array(
  726. 'performance' => array(
  727. 'title' => 'Performance logging',
  728. 'data' => 'No performance data found.',
  729. ),
  730. );
  731. }
  732. return array(
  733. 'performance' => array(
  734. 'title' => 'Performance logging',
  735. 'data' => array(
  736. 'Total number of page accesses' => array($data['total_accesses']),
  737. 'Average duration per page' => array($data['ms_avg'], 'ms'),
  738. 'Average memory per page' => array($data['mb_avg'], 'MB'),
  739. 'Average querycount' => array($data['query_count']),
  740. 'Average duration per query' => array($data['ms_query'], 'ms'),
  741. ),
  742. ),
  743. );
  744. }