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
22 * @author Aaron Schulz
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
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();
44 protected $hits = array(
51 protected $expect = array(
59 protected $expectBy = array();
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
71 public function setExpectation( $event, $value, $fname ) {
72 $this->expect
[$event] = isset( $this->expect
[$event] )
73 ?
min( $this->expect
[$event], $value )
75 if ( $this->expect
[$event] == $value ) {
76 $this->expectBy
[$event] = $fname;
81 * Reset performance expectations and hit counters
85 public function resetExpectations() {
86 foreach ( $this->hits
as &$val ) {
90 foreach ( $this->expect
as &$val ) {
94 $this->expectBy
= array();
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
) {
172 } elseif ( !$isWrite && $elapsed < $this->eventThreshold
) {
173 // Not an important query nor slow enough
177 foreach ( $this->dbTrxHoldingLocks
as $name => $info ) {
178 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
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 );
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." );
215 // Fill in the last non-query period...
216 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
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...
226 foreach ( $this->dbTrxMethodTimes
[$name] as $info ) {
227 $elapsed = ( $info[2] - $info[1] );
228 if ( $elapsed >= $this->dbLockThreshold
) {
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 ) );