SpecialLinkSearch: clean up munged query variable handling
[mediawiki.git] / includes / profiler / TransactionProfiler.php
blobb3135585f953242a584643cfcc4c0747ec59bbdf
1 <?php
2 /**
3 * Transaction profiling for contention
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Profiler
22 * @author Aaron Schulz
25 /**
26 * Helper class that detects high-contention DB queries via profiling calls
28 * This class is meant to work with a DatabaseBase object, which manages queries
30 * @since 1.24
32 class TransactionProfiler {
33 /** @var float Seconds */
34 protected $dbLockThreshold = 3.0;
35 /** @var float Seconds */
36 protected $eventThreshold = .25;
38 /** @var array transaction ID => (write start time, list of DBs involved) */
39 protected $dbTrxHoldingLocks = array();
40 /** @var array transaction ID => list of (query name, start time, end time) */
41 protected $dbTrxMethodTimes = array();
43 /** @var array */
44 protected $hits = array(
45 'writes' => 0,
46 'queries' => 0,
47 'conns' => 0,
48 'masterConns' => 0
50 /** @var array */
51 protected $expect = array(
52 'writes' => INF,
53 'queries' => INF,
54 'conns' => INF,
55 'masterConns' => INF,
56 'maxAffected' => INF
58 /** @var array */
59 protected $expectBy = array();
61 /**
62 * Set performance expectations
64 * With conflicting expect, the most specific ones will be used
66 * @param string $event (writes,queries,conns,mConns)
67 * @param integer $value Maximum count of the event
68 * @param string $fname Caller
69 * @since 1.25
71 public function setExpectation( $event, $value, $fname ) {
72 $this->expect[$event] = isset( $this->expect[$event] )
73 ? min( $this->expect[$event], $value )
74 : $value;
75 if ( $this->expect[$event] == $value ) {
76 $this->expectBy[$event] = $fname;
80 /**
81 * Reset performance expectations and hit counters
83 * @since 1.25
85 public function resetExpectations() {
86 foreach ( $this->hits as &$val ) {
87 $val = 0;
89 unset( $val );
90 foreach ( $this->expect as &$val ) {
91 $val = INF;
93 unset( $val );
94 $this->expectBy = array();
97 /**
98 * Mark a DB as having been connected to with a new handle
100 * Note that there can be multiple connections to a single DB.
102 * @param string $server DB server
103 * @param string $db DB name
104 * @param bool $isMaster
106 public function recordConnection( $server, $db, $isMaster ) {
107 // Report when too many connections happen...
108 if ( $this->hits['conns']++ == $this->expect['conns'] ) {
109 $this->reportExpectationViolated( 'conns', "[connect to $server ($db)]" );
111 if ( $isMaster && $this->hits['masterConns']++ == $this->expect['masterConns'] ) {
112 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
117 * Mark a DB as in a transaction with one or more writes pending
119 * Note that there can be multiple connections to a single DB.
121 * @param string $server DB server
122 * @param string $db DB name
123 * @param string $id ID string of transaction
125 public function transactionWritingIn( $server, $db, $id ) {
126 $name = "{$server} ({$db}) (TRX#$id)";
127 if ( isset( $this->dbTrxHoldingLocks[$name] ) ) {
128 wfDebugLog( 'DBPerformance', "Nested transaction for '$name' - out of sync." );
130 $this->dbTrxHoldingLocks[$name] = array(
131 'start' => microtime( true ),
132 'conns' => array(), // all connections involved
134 $this->dbTrxMethodTimes[$name] = array();
136 foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
137 // Track all DBs in transactions for this transaction
138 $info['conns'][$name] = 1;
143 * Register the name and time of a method for slow DB trx detection
145 * This assumes that all queries are synchronous (non-overlapping)
147 * @param string $query Function name or generalized SQL
148 * @param float $sTime Starting UNIX wall time
149 * @param bool $isWrite Whether this is a write query
150 * @param integer $n Number of affected rows
152 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
153 $eTime = microtime( true );
154 $elapsed = ( $eTime - $sTime );
156 if ( $isWrite && $n > $this->expect['maxAffected'] ) {
157 wfDebugLog( 'DBPerformance',
158 "Query affected $n row(s):\n" . $query . "\n" . wfBacktrace( true ) );
161 // Report when too many writes/queries happen...
162 if ( $this->hits['queries']++ == $this->expect['queries'] ) {
163 $this->reportExpectationViolated( 'queries', $query );
165 if ( $isWrite && $this->hits['writes']++ == $this->expect['writes'] ) {
166 $this->reportExpectationViolated( 'writes', $query );
169 if ( !$this->dbTrxHoldingLocks ) {
170 // Short-circuit
171 return;
172 } elseif ( !$isWrite && $elapsed < $this->eventThreshold ) {
173 // Not an important query nor slow enough
174 return;
177 foreach ( $this->dbTrxHoldingLocks as $name => $info ) {
178 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
179 if ( $lastQuery ) {
180 // Additional query in the trx...
181 $lastEnd = $lastQuery[2];
182 if ( $sTime >= $lastEnd ) { // sanity check
183 if ( ( $sTime - $lastEnd ) > $this->eventThreshold ) {
184 // Add an entry representing the time spent doing non-queries
185 $this->dbTrxMethodTimes[$name][] = array( '...delay...', $lastEnd, $sTime );
187 $this->dbTrxMethodTimes[$name][] = array( $query, $sTime, $eTime );
189 } else {
190 // First query in the trx...
191 if ( $sTime >= $info['start'] ) { // sanity check
192 $this->dbTrxMethodTimes[$name][] = array( $query, $sTime, $eTime );
199 * Mark a DB as no longer in a transaction
201 * This will check if locks are possibly held for longer than
202 * needed and log any affected transactions to a special DB log.
203 * Note that there can be multiple connections to a single DB.
205 * @param string $server DB server
206 * @param string $db DB name
207 * @param string $id ID string of transaction
209 public function transactionWritingOut( $server, $db, $id ) {
210 $name = "{$server} ({$db}) (TRX#$id)";
211 if ( !isset( $this->dbTrxMethodTimes[$name] ) ) {
212 wfDebugLog( 'DBPerformance', "Detected no transaction for '$name' - out of sync." );
213 return;
215 // Fill in the last non-query period...
216 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
217 if ( $lastQuery ) {
218 $now = microtime( true );
219 $lastEnd = $lastQuery[2];
220 if ( ( $now - $lastEnd ) > $this->eventThreshold ) {
221 $this->dbTrxMethodTimes[$name][] = array( '...delay...', $lastEnd, $now );
224 // Check for any slow queries or non-query periods...
225 $slow = false;
226 foreach ( $this->dbTrxMethodTimes[$name] as $info ) {
227 $elapsed = ( $info[2] - $info[1] );
228 if ( $elapsed >= $this->dbLockThreshold ) {
229 $slow = true;
230 break;
233 if ( $slow ) {
234 $dbs = implode( ', ', array_keys( $this->dbTrxHoldingLocks[$name]['conns'] ) );
235 $msg = "Sub-optimal transaction on DB(s) [{$dbs}]:\n";
236 foreach ( $this->dbTrxMethodTimes[$name] as $i => $info ) {
237 list( $query, $sTime, $end ) = $info;
238 $msg .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
240 wfDebugLog( 'DBPerformance', $msg );
242 unset( $this->dbTrxHoldingLocks[$name] );
243 unset( $this->dbTrxMethodTimes[$name] );
247 * @param string $expect
248 * @param string $query
250 protected function reportExpectationViolated( $expect, $query ) {
251 $n = $this->expect[$expect];
252 $by = $this->expectBy[$expect];
253 wfDebugLog( 'DBPerformance',
254 "Expectation ($expect <= $n) by $by not met:\n$query\n" . wfBacktrace( true ) );