SQLStatsPlugin.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2011, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. if (!defined('STATUSNET')) {
  20. exit(1);
  21. }
  22. /**
  23. * Check DB queries for filesorts and such and log em.
  24. *
  25. * @package SQLStatsPlugin
  26. * @maintainer Evan Prodromou <evan@status.net>
  27. */
  28. class SQLStatsPlugin extends Plugin
  29. {
  30. protected $queryCount = 0;
  31. protected $queryStart = 0;
  32. protected $queryTimes = array();
  33. protected $queries = array();
  34. function onPluginVersion(array &$versions)
  35. {
  36. $versions[] = array('name' => 'SQLStats',
  37. 'version' => GNUSOCIAL_VERSION,
  38. 'author' => 'Evan Prodromou',
  39. 'homepage' => 'http://status.net/wiki/Plugin:SQLStats',
  40. 'rawdescription' =>
  41. // TRANS: Plugin decription.
  42. _m('Debug tool to watch for poorly indexed DB queries.'));
  43. return true;
  44. }
  45. function onStartDBQuery($obj, $query, &$result)
  46. {
  47. $this->queryStart = microtime(true);
  48. return true;
  49. }
  50. function onEndDBQuery($obj, $query, &$result)
  51. {
  52. $endTime = microtime(true);
  53. $this->queryTimes[] = round(($endTime - $this->queryStart) * 1000);
  54. $this->queries[] = trim(preg_replace('/\s/', ' ', $query));
  55. $this->queryStart = 0;
  56. return true;
  57. }
  58. function cleanup()
  59. {
  60. if (count($this->queryTimes) == 0) {
  61. $this->log(LOG_INFO, sprintf('0 queries this hit.'));
  62. } else {
  63. $this->log(LOG_INFO, sprintf('%d queries this hit (total = %d, avg = %d, max = %d, min = %d)',
  64. count($this->queryTimes),
  65. array_sum($this->queryTimes),
  66. array_sum($this->queryTimes)/count($this->queryTimes),
  67. max($this->queryTimes),
  68. min($this->queryTimes)));
  69. }
  70. $verbose = common_config('sqlstats', 'verbose');
  71. if ($verbose) {
  72. foreach ($this->queries as $query) {
  73. $this->log(LOG_INFO, $query);
  74. }
  75. }
  76. }
  77. }