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 protected $affectedThreshold = 500;
40 /** @var array transaction ID => (write start time, list of DBs involved) */
41 protected $dbTrxHoldingLocks = array();
42 /** @var array transaction ID => list of (query name, start time, end time) */
43 protected $dbTrxMethodTimes = array();
46 protected $hits = array(
53 protected $expect = array(
60 protected $expectBy = array();
63 * Set performance expectations
65 * With conflicting expect, the most specific ones will be used
67 * @param string $event (writes,queries,conns,mConns)
68 * @param integer $value Maximum count of the event
69 * @param string $fname Caller
72 public function setExpectation( $event, $value, $fname ) {
73 $this->expect
[$event] = isset( $this->expect
[$event] )
74 ?
min( $this->expect
[$event], $value )
76 if ( $this->expect
[$event] == $value ) {
77 $this->expectBy
[$event] = $fname;
82 * Reset performance expectations and hit counters
86 public function resetExpectations() {
87 foreach ( $this->hits
as &$val ) {
91 foreach ( $this->expect
as &$val ) {
95 $this->expectBy
= array();
99 * Mark a DB as having been connected to with a new handle
101 * Note that there can be multiple connections to a single DB.
103 * @param string $server DB server
104 * @param string $db DB name
105 * @param bool $isMaster
107 public function recordConnection( $server, $db, $isMaster ) {
108 // Report when too many connections happen...
109 if ( $this->hits
['conns']++
== $this->expect
['conns'] ) {
110 $this->reportExpectationViolated( 'conns', "[connect to $server ($db)]" );
112 if ( $isMaster && $this->hits
['masterConns']++
== $this->expect
['masterConns'] ) {
113 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
118 * Mark a DB as in a transaction with one or more writes pending
120 * Note that there can be multiple connections to a single DB.
122 * @param string $server DB server
123 * @param string $db DB name
124 * @param string $id ID string of transaction
126 public function transactionWritingIn( $server, $db, $id ) {
127 $name = "{$server} ({$db}) (TRX#$id)";
128 if ( isset( $this->dbTrxHoldingLocks
[$name] ) ) {
129 wfDebugLog( 'DBPerformance', "Nested transaction for '$name' - out of sync." );
131 $this->dbTrxHoldingLocks
[$name] = array(
132 'start' => microtime( true ),
133 'conns' => array(), // all connections involved
135 $this->dbTrxMethodTimes
[$name] = array();
137 foreach ( $this->dbTrxHoldingLocks
as $name => &$info ) {
138 // Track all DBs in transactions for this transaction
139 $info['conns'][$name] = 1;
144 * Register the name and time of a method for slow DB trx detection
146 * This assumes that all queries are synchronous (non-overlapping)
148 * @param string $query Function name or generalized SQL
149 * @param float $sTime Starting UNIX wall time
150 * @param bool $isWrite Whether this is a write query
151 * @param integer $n Number of affected rows
153 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
154 $eTime = microtime( true );
155 $elapsed = ( $eTime - $sTime );
157 if ( $isWrite && $n > $this->affectedThreshold
&& PHP_SAPI
!== 'cli' ) {
158 wfDebugLog( 'DBPerformance',
159 "Query affected $n rows:\n" . $query . "\n" . wfBacktrace( true ) );
162 // Report when too many writes/queries happen...
163 if ( $this->hits
['queries']++
== $this->expect
['queries'] ) {
164 $this->reportExpectationViolated( 'queries', $query );
166 if ( $isWrite && $this->hits
['writes']++
== $this->expect
['writes'] ) {
167 $this->reportExpectationViolated( 'writes', $query );
170 if ( !$this->dbTrxHoldingLocks
) {
173 } elseif ( !$isWrite && $elapsed < $this->eventThreshold
) {
174 // Not an important query nor slow enough
178 foreach ( $this->dbTrxHoldingLocks
as $name => $info ) {
179 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
181 // Additional query in the trx...
182 $lastEnd = $lastQuery[2];
183 if ( $sTime >= $lastEnd ) { // sanity check
184 if ( ( $sTime - $lastEnd ) > $this->eventThreshold
) {
185 // Add an entry representing the time spent doing non-queries
186 $this->dbTrxMethodTimes
[$name][] = array( '...delay...', $lastEnd, $sTime );
188 $this->dbTrxMethodTimes
[$name][] = array( $query, $sTime, $eTime );
191 // First query in the trx...
192 if ( $sTime >= $info['start'] ) { // sanity check
193 $this->dbTrxMethodTimes
[$name][] = array( $query, $sTime, $eTime );
200 * Mark a DB as no longer in a transaction
202 * This will check if locks are possibly held for longer than
203 * needed and log any affected transactions to a special DB log.
204 * Note that there can be multiple connections to a single DB.
206 * @param string $server DB server
207 * @param string $db DB name
208 * @param string $id ID string of transaction
210 public function transactionWritingOut( $server, $db, $id ) {
211 $name = "{$server} ({$db}) (TRX#$id)";
212 if ( !isset( $this->dbTrxMethodTimes
[$name] ) ) {
213 wfDebugLog( 'DBPerformance', "Detected no transaction for '$name' - out of sync." );
216 // Fill in the last non-query period...
217 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
219 $now = microtime( true );
220 $lastEnd = $lastQuery[2];
221 if ( ( $now - $lastEnd ) > $this->eventThreshold
) {
222 $this->dbTrxMethodTimes
[$name][] = array( '...delay...', $lastEnd, $now );
225 // Check for any slow queries or non-query periods...
227 foreach ( $this->dbTrxMethodTimes
[$name] as $info ) {
228 $elapsed = ( $info[2] - $info[1] );
229 if ( $elapsed >= $this->dbLockThreshold
) {
235 $dbs = implode( ', ', array_keys( $this->dbTrxHoldingLocks
[$name]['conns'] ) );
236 $msg = "Sub-optimal transaction on DB(s) [{$dbs}]:\n";
237 foreach ( $this->dbTrxMethodTimes
[$name] as $i => $info ) {
238 list( $query, $sTime, $end ) = $info;
239 $msg .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
241 wfDebugLog( 'DBPerformance', $msg );
243 unset( $this->dbTrxHoldingLocks
[$name] );
244 unset( $this->dbTrxMethodTimes
[$name] );
248 * @param string $expect
249 * @param string $query
251 protected function reportExpectationViolated( $expect, $query ) {
252 $n = $this->expect
[$expect];
253 $by = $this->expectBy
[$expect];
254 wfDebugLog( 'DBPerformance',
255 "Expectation ($expect <= $n) by $by not met:\n$query\n" . wfBacktrace( true ) );