summaryrefslogtreecommitdiffstats
path: root/performance/performance.module
blob: fd4674268592e5a4e52f946c6671053e655047b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
<?php

/**
 * @file
 *
 * Logs detailed and/or summary page generation time and memory
 * consumption for page requests.
 *
 * Copyright Khalid Baheyeldin 2008 of http://2bits.com
 */

define('PERFORMANCE_KEY',          'dru-perf:'. $_SERVER['HTTP_HOST'] .':');
define('PERFORMANCE_MEMCACHE_BIN', 'cache_performance');

function performance_memcache_enabled() {
  global $conf;

  if (function_exists('dmemcache_set') && isset($conf['memcache_bins']['cache_performance'])) {
    return TRUE;
  }
  return FALSE;
}

function performance_menu() {
  $items = array();

  $items['admin/settings/performance_logging'] = array(
    'title'            => 'Performance logging',
    'description'      => 'Logs performance data: page generation times and memory usage.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('performance_settings'),
    'access arguments' => array('access administration pages'),
  );

  $items['admin/settings/performance_logging/apc_clear'] = array(
    'title'            => 'Clear APC',
    'description'      => 'Clears performance statistics collected in APC.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('performance_clear_apc_confirm'),
    'access arguments' => array('access administration pages'),
  );

  $items['admin/settings/performance_logging/memcache_clear'] = array(
    'title'            => 'Clear Memcache',
    'description'      => 'Clears performance statistics collected in Memcache.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('performance_clear_memcache_confirm'),
    'access arguments' => array('access administration pages'),
  );

  $items['admin/reports/performance_logging_summary'] = array(
    'title'            => 'Performance Logs: Summary',
    'description'      => 'View summary performance logs: page generation times and memory usage.',
    'page callback'    => 'performance_view_summary',
    'access arguments' => array('access site reports'),
  );

  $items['admin/reports/performance_logging_details'] = array(
    'title'            => 'Performance Logs: Details',
    'description'      => 'View detailed, per page, performance logs: page generation times and memory usage.',
    'page callback'    => 'performance_view_details',
    'access arguments' => array('access site reports'),
  );

  return $items;
}

function performance_settings() {
  $options = array(
    0 => t('Disabled'),
    1 => t('Enabled'),
  );

  if (function_exists('apc_cache_info')) {
    drupal_set_message(t('APC is enabled. It is reasonably safe to enable summary logging on live sites.'), 'status', FALSE);
  }
  else {
    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', FALSE);
  }

  $form['mode'] = array(
    '#type'  => 'fieldset',
    '#title' => t('Logging mode'),
    '#collapsible' => TRUE,
  );

  $form['mode']['performance_detail'] = array(
    '#type'          => 'select',
    '#title'         => t('Detailed logging'),
    '#default_value' => variable_get('performance_detail', 0),
    '#options'       => $options,
    '#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.'),
  );

  $form['mode']['performance_summary_db'] = array(
    '#type'          => 'select',
    '#title'         => t('Summary logging (DB)'),
    '#default_value' => variable_get('performance_summary_db', 0),
    '#options'       => $options,
    '#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.'),
  );

  $disabled = TRUE;
  if (function_exists('apc_cache_info')) {
    $disabled = FALSE;
  }

  $form['mode']['performance_summary_apc'] = array(
    '#type'          => 'select',
    '#title'         => t('Summary logging (APC)'),
    '#default_value' => variable_get('performance_summary_apc', 0),
    '#options'       => $options,
    '#disabled'      => $disabled,
    '#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.'),
  );

  $disabled = TRUE;
  if (performance_memcache_enabled()) {
    $disabled = FALSE;
  }

  $form['mode']['performance_summary_memcache'] = array(
    '#type'          => 'select',
    '#title'         => t('Summary logging (Memcached)'),
    '#default_value' => variable_get('performance_summary_memcache', 0),
    '#options'       => $options,
    '#disabled'      => $disabled,
    '#description'   => t('Log summary data, such as average and maximum page generation times and memory usage to Memcached, if installed. The summary will be stored in Memcached memory, and hence there is no load on the database. This logging to Memcached is suitable for most live sites, unless the number of unique page accesses is excessively high.'),
  );

  $form['other'] = array(
    '#type'  => 'fieldset',
    '#title' => t('Other'),
    '#collapsible' => TRUE,
  );

  $form['other']['dev_query'] = array(
    '#type'          => 'select',
    '#disabled'      => TRUE,
    '#title'         => t('Database Query timing and count'),
    '#default_value' => variable_get('dev_query', 0),
    '#options'       => $options,
    '#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. Please note that this settings is enabled or disabled in the settings of the devel module.'),
  );

  $form['other']['performance_threshold_accesses'] = array(
    '#type'          => 'select',
    '#title'         => t('Accesses threshold'),
    '#default_value' => variable_get('performance_threshold_accesses', 0),
    '#options'       => array(0, 1, 2, 5, 10),
    '#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.'),
  );

  return system_settings_form($form);
}

function performance_boot() {
  register_shutdown_function('performance_shutdown');
}

function performance_shutdown() {
  global $queries;

//  if ($_GET['q']) {
  if (isset($_GET['q']) && ($_GET['q'])) {
    // q= has a value, use that for the path
    $path = $_GET['q'];
  }
  else {
    // q= is empty, use whatever the site_frontpage is set to
    $path = variable_get('site_frontpage', 'node');
  }

  $params = array(
    'timer' => timer_read('page'),
    'path'  => $path,
  );

  // Memory
  if (function_exists('memory_get_peak_usage')) {
    $params['mem'] = memory_get_peak_usage(TRUE);
  }
  else {
    $params['mem'] = 0;
  }

  // Query time and count
  $query_count = 0;
  $query_timer = 0;
  $sum = 0;
  if (variable_get('dev_query', 0) && is_array($queries)) {
    foreach ($queries as $query) {
      $sum += $query[1];
    }
    $query_count = count($queries);
    $query_timer = round($sum * 1000, 2);
  }

  $params['query_count'] = $query_count;
  $params['query_timer'] = $query_timer;

  $anon = (!empty($data['anon']))? 'Yes' : 'No';

  $header = array(
    'path' => $path,
    'timer' => $params['timer'],
    'anon' => $anon,
  );
  module_invoke_all('performance', 'header', $header);

  if (variable_get('performance_detail', 0)) {
    $data = module_invoke_all('performance', 'data');
    if (!empty($data[0])) {
      $params['data'] = $data[0];
    }

    performance_log_details($params);
  }
  else {
    module_invoke_all('performance', 'disable');
  }

  if (variable_get('performance_summary_db', 0)) {
    performance_log_summary_db($params);
  }

  if (variable_get('performance_summary_apc', 0)) {
    if (function_exists('apc_cache_info')) {
      performance_log_summary_apc($params);
    }
  }

  if (variable_get('performance_summary_memcache', 0)) {
    if (performance_memcache_enabled()) {
      performance_log_summary_memcache($params);
    }
  }
}

function performance_log_summary_apc($params = array()) {
  $key = PERFORMANCE_KEY . $params['path'];
  if ($data = apc_fetch($key)) {
    $data = array(
      'path'            => $data['path'],
      'last_access'     => time(),
      'bytes_max'       => max($params['mem'], $data['bytes_max']),
      'bytes_avg'       => ($data['bytes_avg'] + $params['mem']) / 2,
      'ms_max'          => max($params['timer'], $data['ms_max']),
      'ms_avg'          => ($data['ms_avg'] + $params['timer']) / 2,
      'query_timer_max' => max($params['query_timer'], $data['query_timer_max']),
      'query_timer_avg' => ($data['query_timer_avg'] + $params['query_timer']) / 2,
      'query_count_max' => max($params['query_count'], $data['query_count_max']),
      'query_count_avg' => ($data['query_count_avg'] + $params['query_count']) / 2,
      'num_accesses'    => $data['num_accesses'] + 1,
    );
  }
  else {
    $data = array(
      'path'            => $params['path'],
      'bytes_max'       => $params['mem'],
      'bytes_avg'       => $params['mem'],
      'ms_max'          => $params['timer'],
      'ms_avg'          => $params['timer'],
      'query_timer_max' => $params['query_timer'],
      'query_timer_avg' => $params['query_timer'],
      'query_count_max' => $params['query_count'],
      'query_count_avg' => $params['query_count'],
      'num_accesses'    => 1,
      'last_access'     => time(),
    );
  }
  apc_store($key, $data);
}

function performance_log_summary_memcache($params = array()) {
  $key = PERFORMANCE_KEY . $params['path'];
  if ($cache = cache_get($key, PERFORMANCE_MEMCACHE_BIN)) {
    $type = 'existing';
    $values = $cache->data;
    $values = array(
      'path'            => $params['path'],
      'last_access'     => time(),
      'bytes_max'       => max($params['mem'], $values['bytes_max']),
      'bytes_avg'       => ($values['bytes_avg'] + $params['mem']) / 2,
      'ms_max'          => max($params['timer'], $values['ms_max']),
      'ms_avg'          => ($values['ms_avg'] + $params['timer']) / 2,
      'query_timer_max' => max($params['query_timer'], $values['query_timer_max']),
      'query_timer_avg' => ($values['query_timer_avg'] + $params['query_timer']) / 2,
      'query_count_max' => max($params['query_count'], $values['query_count_max']),
      'query_count_avg' => ($values['query_count_avg'] + $params['query_count']) / 2,
      'num_accesses'    => $values['num_accesses'] + 1,
    );
  }
  else {
    $type = 'new';
    // It is a new key
    $values = array(
      'path'            => $params['path'],
      'bytes_max'       => $params['mem'],
      'bytes_avg'       => $params['mem'],
      'ms_max'          => $params['timer'],
      'ms_avg'          => $params['timer'],
      'query_timer_max' => $params['query_timer'],
      'query_timer_avg' => $params['query_timer'],
      'query_count_max' => $params['query_count'],
      'query_count_avg' => $params['query_count'],
      'num_accesses'    => 1,
      'last_access'     => time(),
    );

    if ($keys_cache = cache_get(PERFORMANCE_KEY, PERFORMANCE_MEMCACHE_BIN)) {
      $keys_values = $keys_cache->data;
    }
    $keys_values[$key] = 1;
    cache_set(PERFORMANCE_KEY, $keys_values, PERFORMANCE_MEMCACHE_BIN, CACHE_PERMANENT);
  }
  cache_set($key, $values, PERFORMANCE_MEMCACHE_BIN, CACHE_PERMANENT);
}

function performance_log_summary_db($params = array()) {
  $row = db_fetch_object(db_query("SELECT * FROM {performance_summary} WHERE path = '%s'", $params['path']));
  if (!empty($row)) {
    db_query("UPDATE {performance_summary}
      SET last_access = %d,
      num_accesses = num_accesses + 1,
      bytes_max = %d,
      bytes_avg = %d,
      ms_max = %d,
      ms_avg = %d,
      query_timer_max = %d,
      query_timer_avg = %d,
      query_count_max = %d,
      query_count_avg = %d
      WHERE path = '%s'",
      time(),
      max($params['mem'], $row->bytes_max),
      ($row->bytes_avg + $params['mem']) / 2,
      max($params['timer'], $row->ms_max),
      ($row->ms_avg + $params['timer']) / 2,
      max($params['query_timer'], $row->query_timer_max),
      ($row->query_timer_avg + $params['query_timer']) / 2,
      max($params['query_count'], $row->query_count_max),
      ($row->query_count_avg + $params['query_count']) / 2,
      $params['path']);
  }
  else {
    // First time we log this path, write fresh values
    db_query("INSERT INTO {performance_summary}
      (path, last_access, num_accesses,
      bytes_max, bytes_avg, ms_max, ms_avg,
      query_count_max, query_count_avg, query_timer_max, query_timer_avg)
      VALUES
      ('%s', %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
      $params['path'],
      time(),
      1,
      $params['mem'],
      $params['mem'],
      $params['timer'],
      $params['timer'],
      $params['query_count'],
      $params['query_count'],
      $params['query_timer'],
      $params['query_timer']
    );
  }
}

function performance_log_details($params = array()) {
  global $user;
  $anon = ($user->uid) ? FALSE : TRUE;
  db_query("INSERT INTO {performance_detail} (path, anon, bytes, ms, timestamp, query_timer, query_count, data) VALUES ('%s', %d, %d, %d, %d, %d, %d, '%s')",
    $params['path'],
    $anon,
    $params['mem'],
    $params['timer'],
    time(),
    $params['query_timer'],
    $params['query_count'],
    $params['data']
  );
}

function performance_apc_list_all() {
  $key_list = array();
  $list = apc_cache_info('user');
  if (!empty($list['cache_list'])) {
    foreach ($list['cache_list'] as $cache_id => $cache_data) {
      $regex = '/^'. PERFORMANCE_KEY .'/';
      if (preg_match($regex, $cache_data['info'])) {
        $key_list[] = $cache_data['info'];
      }
    }
  }
  return $key_list;
}

/**
 * Custom sort for summary performance report
 *
 * @param $x
 * @param $y
 * @return int
 */
function performance_summary_sort($x, $y) {
  // This function is not working
  return 0;
}

function performance_view_summary() {
  $sum = array();
  $data_list = array();
  $rows = array();

  $sum[] = variable_get('performance_summary_db', 0);
  $sum[] = variable_get('performance_summary_apc', 0);
  $sum[] = variable_get('performance_summary_memcache', 0);
  $go = array_sum($sum);

  if (!$go) {
    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')));
  }

  $header = array();

  $header[] =  array('data' => t('Path'),               'field' => 'path');
  $header[] =  array('data' => t('Last access'),        'field' => 'last_access');
  $header[] =  array('data' => t('# accesses'),         'field' => 'num_accesses');
  $header[] =  array('data' => t('Max Memory (MB)'),    'field' => 'bytes_max');
  $header[] =  array('data' => t('Avg Memory (MB)'),    'field' => 'bytes_avg');
  $header[] =  array('data' => t('ms (Max)'),           'field' => 'ms_max');
  $header[] =  array('data' => t('ms (Avg)'),           'field' => 'ms_avg');

  if (variable_get('dev_query', 0)) {
    $header[] = array('data' => t('Query ms (Max)'),    'field' => 'query_timer_max');
    $header[] = array('data' => t('Query ms (Avg)'),    'field' => 'query_timer_avg');
    $header[] = array('data' => t('Query Count (Max)'), 'field' => 'query_count_max');
    $header[] = array('data' => t('Query Count (Avg)'), 'field' => 'query_count_avg');
  }

  $total_rows = $shown = $last_max = $total_bytes = $total_ms = $total_accesses = 0;
  $last_min = time();

  $threshold = variable_get('performance_threshold_accesses', 0);

  if (variable_get('performance_summary_memcache', 0) && performance_memcache_enabled()) {
    $tablesort = tablesort_init($header);
    // Get the data from memcache
    if ($keys_cache = cache_get(PERFORMANCE_KEY, PERFORMANCE_MEMCACHE_BIN)) {
      if ($keys_cache->data) {
        foreach ($keys_cache->data as $key => $v) {
          $cache = cache_get($key, PERFORMANCE_MEMCACHE_BIN);
          $data_list[] = $cache->data;
        }
      }
    }
    usort($data_list, 'performance_summary_sort');
  }
  else if (variable_get('performance_summary_apc', 0) && function_exists('apc_cache_info')) {
    $tablesort = tablesort_init($header);
    // Get the data from the APC cache
    foreach (performance_apc_list_all() as $key) {
      $data_list[] = apc_fetch($key) + $tablesort;
    }
    usort($data_list, 'performance_summary_sort');
  }
  else {
    // Get the data form the database table
    $sql = "SELECT * FROM {performance_summary}";
    $tablesort = tablesort_sql($header);
    $result = pager_query($sql . $tablesort, 50);
    while ($row = db_fetch_array($result)) {
      $data_list[] = $row;
    }
  }

  foreach ($data_list as $data) {
    $total_rows++;
    $last_max = max($last_max, $data['last_access']);
    $last_min = min($last_min, $data['last_access']);

    // Calculate running averages
    $total_bytes += $data['bytes_avg'];
    $total_ms += $data['ms_avg'];
    $total_accesses += $data['num_accesses'];

    $row_data = array();

    if ($data['num_accesses'] > $threshold) {
      $shown++;
      $row_data[] = check_plain($data['path']);
      $row_data[] = format_date($data['last_access'], 'small');
      $row_data[] = $data['num_accesses'];
      $row_data[] = number_format($data['bytes_max']/1024/1024, 2);
      $row_data[] = number_format($data['bytes_avg']/1024/1024, 2);
      $row_data[] = number_format($data['ms_max'], 1);
      $row_data[] = number_format($data['ms_avg'], 1);
      if (variable_get('dev_query', 0)) {
        $row_data[] = number_format($data['query_timer_max'], 1);
        $row_data[] = number_format($data['query_timer_avg'], 1);
        $row_data[] = $data['query_count_max'];
        $row_data[] = $data['query_count_avg'];
      }
    }
    $rows[] = array('data' => $row_data);
  }

  if (!$rows) {
    $rows[] = array(array('data' => t('No statistics available yet.'), 'colspan' => count($header)));
  }

  $output = '';
  if ($threshold) {
    $output .= t('Showing !shown paths with more than !threshold accesses, out of !total total paths.',
      array('!threshold' => $threshold, '!shown' => $shown, '!total' => $total_rows)) .'<br/>';
  }
  else {
    $output .= t('Showing all !total paths.', array('!total' => $total_rows)) .'<br/>';
  }

  // Protect against divide by zero
  if ($total_rows > 0) {
    $mb_avg = number_format($total_bytes/$total_rows/1024/1024, 1);
    $ms_avg = number_format($total_ms/$total_rows, 2);
  }
  else {
    $mb_avg = 'n/a';
    $ms_avg = 'n/a';
  }

  $output .= t('Average memory per page: !mb_avg MB', array('!mb_avg' => $mb_avg)) .'<br/>';
  $output .= t('Average ms per page: !ms_avg', array('!ms_avg' => $ms_avg)) .'<br/>';
  $output .= t('Total number of page accesses: !accesses', array('!accesses' => $total_accesses)) .'<br/>';
  $output .= t('First access: !access.', array('!access' => format_date($last_min, 'small'))) .'<br/>';
  $output .= t('Last access: !access.',  array('!access' => format_date($last_max, 'small'))) .'<br/>';

  $output .= theme('table', $header, $rows);
  $output .= theme('pager', NULL, 50, 0);

  return $output;
}

function performance_view_details() {
  if (!variable_get('performance_detail', 0)) {
    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')));
  }

  $header = array(
    array('data' => t('#'),                     'field' => 'pid', 'sort' => 'desc'),
    array('data' => t('Date'),                  'field' => 'timestamp'),
    array('data' => t('Path'),                  'field' => 'path'),
    array('data' => t('Memory (MB)'),           'field' => 'bytes'),
    array('data' => t('ms (Total)'),            'field' => 'ms'),
    array('data' => t('Anonymous?'),            'field' => 'anon'),
  );

  if (variable_get('dev_query', 0)) {
    $header[] = array('data' => t('# Queries'), 'field' => 'query_count');
    $header[] = array('data' => t('Query ms'),  'field' => 'query_timer');
  }

  $sql = "SELECT * FROM {performance_detail}";
  $tablesort = tablesort_sql($header);
  $result = pager_query($sql . $tablesort, 50);

  while ($data = db_fetch_array($result)) {
    $row_data = array();

    $row_data[] = $data['pid'];
    $row_data[] = format_date($data['timestamp'], 'small');
    $row_data[] = check_plain($data['path']);
    $row_data[] = number_format($data['bytes']/1024/1024, 2);
    $row_data[] = $data['ms'];
    $row_data[] = ($data['anon']) ? t('Yes') : t('No');

    if (variable_get('dev_query', 0)) {
      $row_data[] = $data['query_count'];
      $row_data[] = $data['query_timer'];
    }

    $rows[] = array('data' => $row_data);
  }

  if (!$rows) {
    $rows[] = array(array('data' => t('No log messages available.'), 'colspan' => count($header)));
  }

  $output  = theme('table', $header, $rows);
  $output .= theme('pager', NULL, 50, 0);

  return $output;
}

function performance_cron() {
  // One day ago ...
  $timestamp = time() - 24*60*60;

  performance_cron_db_prune($timestamp);
  performance_cron_apc_prune($timestamp);
}

function performance_cron_db_prune($timestamp = 0) {
  // Remove rows which have not been accessed since a certain timestamp
  db_query("DELETE FROM {performance_summary} WHERE last_access <= %d", $timestamp);

  // Remove performance_detail rows on a daily basis
  db_query("DELETE FROM {performance_detail} WHERE timestamp <= %d", $timestamp);
}

function performance_cron_apc_prune($timestamp = 0) {
  if (!function_exists('apc_cache_info')) {
    // APC not enabled, nothing to do ...
    return;
  }

  // Get all entries in APC's user cache
  $list = performance_apc_list_all();
  if (!count($list)) {
    // Nothing stored yet
    return;
  }

  foreach ($list as $key) {
    if ($data = apc_fetch($key)) {
      if ($data['last_access'] <= $timestamp) {
        apc_delete($key);
      }
    }
  }
}

function performance_clear_apc_confirm() {
  $form['confirm'] = array(
    '#value' => t('Confirm APC clear'),
  );
  return confirm_form(
    $form,
    t('Are you sure you want to clear the APC statistics for this site?'),
    'admin/settings/performance_logging',
    t('This will clear all the collected performance statistics stored in APC. This action cannot be undone.'),
    t('Clear'),
    t('Cancel'));
}

function performance_clear_apc_confirm_submit($form, &$form_state) {
  if (!function_exists('apc_cache_info')) {
    drupal_set_message(t('APC is not enabled. Nothing to do ...'), 'status', FALSE);
    drupal_goto('admin/settings/performance');
    return;
  }

  $list = performance_apc_list_all();
  if (!count($list)) {
    // Nothing stored yet
    return;
  }

  foreach ($list as $key) {
    if ($data = apc_fetch($key)) {
      apc_delete($key);
    }
  }

  drupal_set_message(t('Performance statistics collected in APC has been cleared.'), 'status', FALSE);
  drupal_goto('admin/settings/performance');
}

function performance_clear_memcache_confirm() {
  $form['confirm'] = array(
    '#value' => t('Confirm Memcache clear'),
  );
  return confirm_form(
    $form,
    t('Are you sure you want to clear the Memcache statistics for this site?'),
    'admin/settings/performance_logging',
    t('This will clear all the collected performance statistics stored in Memcache. This action cannot be undone.'),
    t('Clear'),
    t('Cancel'));
}

function performance_clear_memcache_confirm_submit($form, &$form_state) {
  if (!performance_memcache_enabled()) {
    drupal_set_message(t('Memcache is not enabled. Nothing to do ...'), 'status', FALSE);
    drupal_goto('admin/settings/performance');
    return;
  }

  // We have to iterate over all entries and delete them, reaching down
  // the API stack and calling dmemcache_delete directly.
  // This is suboptimal, but there is no other alternative
  if ($keys_cache = cache_get(PERFORMANCE_KEY, PERFORMANCE_MEMCACHE_BIN)) {
    if ($keys_cache->data) {
      foreach ($keys_cache->data as $key => $v) {
        dmemcache_delete($key, PERFORMANCE_MEMCACHE_BIN);
      }
      dmemcache_delete(PERFORMANCE_KEY, PERFORMANCE_MEMCACHE_BIN);
    }
  }

  drupal_set_message(t('Performance statistics collected in Memcache has been cleared.'), 'status', FALSE);
  drupal_goto('admin/settings/performance');
}

/**
 * Implementation of hook_nagios_info().
 */
function performance_nagios_info() {
  return array(
    'name'   => 'Performance logging',
    'id'     => 'PERF',
  );
}

/**
 * Implementation of hook_nagios().
 */
function performance_nagios() {
  $info = performance_nagios_info();
  $id = $info['id'];

  // Find out if we have what we need enabled
  $sum = array();

  $sum[] = variable_get('performance_summary_db', 0);
  $sum[] = variable_get('performance_summary_apc', 0);
  $go = array_sum($sum);

  if (!$go) {
    return array(
      $id => array(
        'status' => NAGIOS_STATUS_UNKNOWN,
        'type'   => 'perf',
        'text'   => t('Performance logging is not enabled'),
      ),
    );
  }

  // Initialize variables
  $total_rows = $total_bytes = $total_ms = $total_accesses = $total_query_time = $total_query_count = 0;

  // Check which data store to use
  if (variable_get('performance_summary_apc', 0) && function_exists('apc_cache_info')) {
    // Get the data from the APC cache
    foreach (performance_apc_list_all() as $key) {
      $data_list[] = apc_fetch($key);
    }
  }
  else {
    // Get the data form the database table for URLs that have been accessed in the last 15 minutes
    $result = db_query("SELECT * FROM {performance_summary} WHERE last_access >= %d", time() - 15*60);
    while (is_array($row = db_fetch_array($result))) {
      $data_list[] = $row;
    }
  }

  foreach ($data_list as $data) {
    $total_rows++;

    // Calculate running averages
    $total_bytes       += $data['bytes_avg'];
    $total_ms          += $data['ms_avg'];
    $total_accesses    += $data['num_accesses'];
    $total_query_time  += $data['query_timer_avg'];
    $total_query_count += $data['query_count_avg'];
  }

  // Protect against divide by zero
  if ($total_rows > 0) {
    $ms_avg      = number_format($total_ms          / $total_rows, 1, '.', '');
    $ms_query    = number_format($total_query_time  / $total_rows, 1, '.', '');
    $query_count = number_format($total_query_count / $total_rows, 2, '.', '');
    $mb_avg      = number_format($total_bytes       / $total_rows/1024/1024, 1);
  }
  else {
    $ms_avg = '';
    $ms_query = '';
    $mb_avg = '';
    $query_count = '';
  }

  $status = NAGIOS_STATUS_OK;

  return array(
    'ACC' => array(
      'status' => $status,
      'type'   => 'perf',
      'text'   => $total_accesses,
    ),
    'MS' => array(
      'status' => $status,
      'type'   => 'perf',
      'text'   => $ms_avg,
    ),
    'MMB' => array(
      'status' => $status,
      'type'   => 'perf',
      'text'   => $mb_avg,
    ),
    'QRC' => array(
      'status' => $status,
      'type'   => 'perf',
      'text'   => $query_count,
    ),
    'QRT' => array(
      'status' => $status,
      'type'   => 'perf',
      'text'   => $ms_query,
    ),
  );
}