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
25 use Psr\Log\LoggerInterface
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\NullLogger
;
30 * Helper class that detects high-contention DB queries via profiling calls
32 * This class is meant to work with a DatabaseBase object, which manages queries
36 class TransactionProfiler
implements LoggerAwareInterface
{
37 /** @var float Seconds */
38 protected $dbLockThreshold = 3.0;
39 /** @var float Seconds */
40 protected $eventThreshold = .25;
42 /** @var array transaction ID => (write start time, list of DBs involved) */
43 protected $dbTrxHoldingLocks = [];
44 /** @var array transaction ID => list of (query name, start time, end time) */
45 protected $dbTrxMethodTimes = [];
61 'readQueryTime' => INF
,
62 'writeQueryTime' => INF
65 protected $expectBy = [];
68 * @var LoggerInterface
72 public function __construct() {
73 $this->setLogger( new NullLogger() );
76 public function setLogger( LoggerInterface
$logger ) {
77 $this->logger
= $logger;
81 * Set performance expectations
83 * With conflicting expectations, the most narrow ones will be used
85 * @param string $event (writes,queries,conns,mConns)
86 * @param integer $value Maximum count of the event
87 * @param string $fname Caller
90 public function setExpectation( $event, $value, $fname ) {
91 $this->expect
[$event] = isset( $this->expect
[$event] )
92 ?
min( $this->expect
[$event], $value )
94 if ( $this->expect
[$event] == $value ) {
95 $this->expectBy
[$event] = $fname;
100 * Set multiple performance expectations
102 * With conflicting expectations, the most narrow ones will be used
104 * @param array $expects Map of (event => limit)
108 public function setExpectations( array $expects, $fname ) {
109 foreach ( $expects as $event => $value ) {
110 $this->setExpectation( $event, $value, $fname );
115 * Reset performance expectations and hit counters
119 public function resetExpectations() {
120 foreach ( $this->hits
as &$val ) {
124 foreach ( $this->expect
as &$val ) {
128 $this->expectBy
= [];
132 * Mark a DB as having been connected to with a new handle
134 * Note that there can be multiple connections to a single DB.
136 * @param string $server DB server
137 * @param string $db DB name
138 * @param bool $isMaster
140 public function recordConnection( $server, $db, $isMaster ) {
141 // Report when too many connections happen...
142 if ( $this->hits
['conns']++
== $this->expect
['conns'] ) {
143 $this->reportExpectationViolated( 'conns', "[connect to $server ($db)]" );
145 if ( $isMaster && $this->hits
['masterConns']++
== $this->expect
['masterConns'] ) {
146 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
151 * Mark a DB as in a transaction with one or more writes pending
153 * Note that there can be multiple connections to a single DB.
155 * @param string $server DB server
156 * @param string $db DB name
157 * @param string $id ID string of transaction
159 public function transactionWritingIn( $server, $db, $id ) {
160 $name = "{$server} ({$db}) (TRX#$id)";
161 if ( isset( $this->dbTrxHoldingLocks
[$name] ) ) {
162 $this->logger
->info( "Nested transaction for '$name' - out of sync." );
164 $this->dbTrxHoldingLocks
[$name] = [
165 'start' => microtime( true ),
166 'conns' => [], // all connections involved
168 $this->dbTrxMethodTimes
[$name] = [];
170 foreach ( $this->dbTrxHoldingLocks
as $name => &$info ) {
171 // Track all DBs in transactions for this transaction
172 $info['conns'][$name] = 1;
177 * Register the name and time of a method for slow DB trx detection
179 * This assumes that all queries are synchronous (non-overlapping)
181 * @param string $query Function name or generalized SQL
182 * @param float $sTime Starting UNIX wall time
183 * @param bool $isWrite Whether this is a write query
184 * @param integer $n Number of affected rows
186 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
187 $eTime = microtime( true );
188 $elapsed = ( $eTime - $sTime );
190 if ( $isWrite && $n > $this->expect
['maxAffected'] ) {
191 $this->logger
->info( "Query affected $n row(s):\n" . $query . "\n" .
192 wfBacktrace( true ) );
195 // Report when too many writes/queries happen...
196 if ( $this->hits
['queries']++
== $this->expect
['queries'] ) {
197 $this->reportExpectationViolated( 'queries', $query );
199 if ( $isWrite && $this->hits
['writes']++
== $this->expect
['writes'] ) {
200 $this->reportExpectationViolated( 'writes', $query );
202 // Report slow queries...
203 if ( !$isWrite && $elapsed > $this->expect
['readQueryTime'] ) {
204 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
206 if ( $isWrite && $elapsed > $this->expect
['writeQueryTime'] ) {
207 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
210 if ( !$this->dbTrxHoldingLocks
) {
213 } elseif ( !$isWrite && $elapsed < $this->eventThreshold
) {
214 // Not an important query nor slow enough
218 foreach ( $this->dbTrxHoldingLocks
as $name => $info ) {
219 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
221 // Additional query in the trx...
222 $lastEnd = $lastQuery[2];
223 if ( $sTime >= $lastEnd ) { // sanity check
224 if ( ( $sTime - $lastEnd ) > $this->eventThreshold
) {
225 // Add an entry representing the time spent doing non-queries
226 $this->dbTrxMethodTimes
[$name][] = [ '...delay...', $lastEnd, $sTime ];
228 $this->dbTrxMethodTimes
[$name][] = [ $query, $sTime, $eTime ];
231 // First query in the trx...
232 if ( $sTime >= $info['start'] ) { // sanity check
233 $this->dbTrxMethodTimes
[$name][] = [ $query, $sTime, $eTime ];
240 * Mark a DB as no longer in a transaction
242 * This will check if locks are possibly held for longer than
243 * needed and log any affected transactions to a special DB log.
244 * Note that there can be multiple connections to a single DB.
246 * @param string $server DB server
247 * @param string $db DB name
248 * @param string $id ID string of transaction
249 * @param float $writeTime Time spent in write queries
251 public function transactionWritingOut( $server, $db, $id, $writeTime = 0.0 ) {
252 $name = "{$server} ({$db}) (TRX#$id)";
253 if ( !isset( $this->dbTrxMethodTimes
[$name] ) ) {
254 $this->logger
->info( "Detected no transaction for '$name' - out of sync." );
260 // Warn if too much time was spend writing...
261 if ( $writeTime > $this->expect
['writeQueryTime'] ) {
262 $this->reportExpectationViolated(
264 "[transaction $id writes to {$server} ({$db})]",
269 // Fill in the last non-query period...
270 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
272 $now = microtime( true );
273 $lastEnd = $lastQuery[2];
274 if ( ( $now - $lastEnd ) > $this->eventThreshold
) {
275 $this->dbTrxMethodTimes
[$name][] = [ '...delay...', $lastEnd, $now ];
278 // Check for any slow queries or non-query periods...
279 foreach ( $this->dbTrxMethodTimes
[$name] as $info ) {
280 $elapsed = ( $info[2] - $info[1] );
281 if ( $elapsed >= $this->dbLockThreshold
) {
287 $dbs = implode( ', ', array_keys( $this->dbTrxHoldingLocks
[$name]['conns'] ) );
288 $msg = "Sub-optimal transaction on DB(s) [{$dbs}]:\n";
289 foreach ( $this->dbTrxMethodTimes
[$name] as $i => $info ) {
290 list( $query, $sTime, $end ) = $info;
291 $msg .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
293 $this->logger
->info( $msg );
295 unset( $this->dbTrxHoldingLocks
[$name] );
296 unset( $this->dbTrxMethodTimes
[$name] );
300 * @param string $expect
301 * @param string $query
302 * @param string|float|int $actual [optional]
304 protected function reportExpectationViolated( $expect, $query, $actual = null ) {
305 $n = $this->expect
[$expect];
306 $by = $this->expectBy
[$expect];
307 $actual = ( $actual !== null ) ?
" (actual: $actual)" : "";
310 "Expectation ($expect <= $n) by $by not met$actual:\n$query\n" .