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 namespace Wikimedia\Rdbms
;
27 use Psr\Log\LoggerInterface
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\NullLogger
;
33 * Helper class that detects high-contention DB queries via profiling calls
35 * This class is meant to work with an IDatabase object, which manages queries
39 class TransactionProfiler
implements LoggerAwareInterface
{
40 /** @var float Seconds */
41 protected $dbLockThreshold = 3.0;
42 /** @var float Seconds */
43 protected $eventThreshold = .25;
45 protected $silenced = false;
47 /** @var array transaction ID => (write start time, list of DBs involved) */
48 protected $dbTrxHoldingLocks = [];
49 /** @var array transaction ID => list of (query name, start time, end time) */
50 protected $dbTrxMethodTimes = [];
66 'readQueryTime' => INF
,
67 'writeQueryTime' => INF
70 protected $expectBy = [];
73 * @var LoggerInterface
77 public function __construct() {
78 $this->setLogger( new NullLogger() );
81 public function setLogger( LoggerInterface
$logger ) {
82 $this->logger
= $logger;
86 * @param bool $value New value
87 * @return bool Old value
90 public function setSilenced( $value ) {
91 $old = $this->silenced
;
92 $this->silenced
= $value;
98 * Set performance expectations
100 * With conflicting expectations, the most narrow ones will be used
102 * @param string $event (writes,queries,conns,mConns)
103 * @param integer $value Maximum count of the event
104 * @param string $fname Caller
107 public function setExpectation( $event, $value, $fname ) {
108 $this->expect
[$event] = isset( $this->expect
[$event] )
109 ?
min( $this->expect
[$event], $value )
111 if ( $this->expect
[$event] == $value ) {
112 $this->expectBy
[$event] = $fname;
117 * Set multiple performance expectations
119 * With conflicting expectations, the most narrow ones will be used
121 * @param array $expects Map of (event => limit)
125 public function setExpectations( array $expects, $fname ) {
126 foreach ( $expects as $event => $value ) {
127 $this->setExpectation( $event, $value, $fname );
132 * Reset performance expectations and hit counters
136 public function resetExpectations() {
137 foreach ( $this->hits
as &$val ) {
141 foreach ( $this->expect
as &$val ) {
145 $this->expectBy
= [];
149 * Mark a DB as having been connected to with a new handle
151 * Note that there can be multiple connections to a single DB.
153 * @param string $server DB server
154 * @param string $db DB name
155 * @param bool $isMaster
157 public function recordConnection( $server, $db, $isMaster ) {
158 // Report when too many connections happen...
159 if ( $this->hits
['conns']++
>= $this->expect
['conns'] ) {
160 $this->reportExpectationViolated(
161 'conns', "[connect to $server ($db)]", $this->hits
['conns'] );
163 if ( $isMaster && $this->hits
['masterConns']++
>= $this->expect
['masterConns'] ) {
164 $this->reportExpectationViolated(
165 'masterConns', "[connect to $server ($db)]", $this->hits
['masterConns'] );
170 * Mark a DB as in a transaction with one or more writes pending
172 * Note that there can be multiple connections to a single DB.
174 * @param string $server DB server
175 * @param string $db DB name
176 * @param string $id ID string of transaction
178 public function transactionWritingIn( $server, $db, $id ) {
179 $name = "{$server} ({$db}) (TRX#$id)";
180 if ( isset( $this->dbTrxHoldingLocks
[$name] ) ) {
181 $this->logger
->info( "Nested transaction for '$name' - out of sync." );
183 $this->dbTrxHoldingLocks
[$name] = [
184 'start' => microtime( true ),
185 'conns' => [], // all connections involved
187 $this->dbTrxMethodTimes
[$name] = [];
189 foreach ( $this->dbTrxHoldingLocks
as $name => &$info ) {
190 // Track all DBs in transactions for this transaction
191 $info['conns'][$name] = 1;
196 * Register the name and time of a method for slow DB trx detection
198 * This assumes that all queries are synchronous (non-overlapping)
200 * @param string $query Function name or generalized SQL
201 * @param float $sTime Starting UNIX wall time
202 * @param bool $isWrite Whether this is a write query
203 * @param integer $n Number of affected rows
205 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
206 $eTime = microtime( true );
207 $elapsed = ( $eTime - $sTime );
209 if ( $isWrite && $n > $this->expect
['maxAffected'] ) {
211 "Query affected $n row(s):\n" . $query . "\n" .
212 ( new RuntimeException() )->getTraceAsString() );
215 // Report when too many writes/queries happen...
216 if ( $this->hits
['queries']++
>= $this->expect
['queries'] ) {
217 $this->reportExpectationViolated( 'queries', $query, $this->hits
['queries'] );
219 if ( $isWrite && $this->hits
['writes']++
>= $this->expect
['writes'] ) {
220 $this->reportExpectationViolated( 'writes', $query, $this->hits
['writes'] );
222 // Report slow queries...
223 if ( !$isWrite && $elapsed > $this->expect
['readQueryTime'] ) {
224 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
226 if ( $isWrite && $elapsed > $this->expect
['writeQueryTime'] ) {
227 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
230 if ( !$this->dbTrxHoldingLocks
) {
233 } elseif ( !$isWrite && $elapsed < $this->eventThreshold
) {
234 // Not an important query nor slow enough
238 foreach ( $this->dbTrxHoldingLocks
as $name => $info ) {
239 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
241 // Additional query in the trx...
242 $lastEnd = $lastQuery[2];
243 if ( $sTime >= $lastEnd ) { // sanity check
244 if ( ( $sTime - $lastEnd ) > $this->eventThreshold
) {
245 // Add an entry representing the time spent doing non-queries
246 $this->dbTrxMethodTimes
[$name][] = [ '...delay...', $lastEnd, $sTime ];
248 $this->dbTrxMethodTimes
[$name][] = [ $query, $sTime, $eTime ];
251 // First query in the trx...
252 if ( $sTime >= $info['start'] ) { // sanity check
253 $this->dbTrxMethodTimes
[$name][] = [ $query, $sTime, $eTime ];
260 * Mark a DB as no longer in a transaction
262 * This will check if locks are possibly held for longer than
263 * needed and log any affected transactions to a special DB log.
264 * Note that there can be multiple connections to a single DB.
266 * @param string $server DB server
267 * @param string $db DB name
268 * @param string $id ID string of transaction
269 * @param float $writeTime Time spent in write queries
270 * @param integer $affected Number of rows affected by writes
272 public function transactionWritingOut( $server, $db, $id, $writeTime = 0.0, $affected = 0 ) {
273 $name = "{$server} ({$db}) (TRX#$id)";
274 if ( !isset( $this->dbTrxMethodTimes
[$name] ) ) {
275 $this->logger
->info( "Detected no transaction for '$name' - out of sync." );
281 // Warn if too much time was spend writing...
282 if ( $writeTime > $this->expect
['writeQueryTime'] ) {
283 $this->reportExpectationViolated(
285 "[transaction $id writes to {$server} ({$db})]",
290 // Warn if too many rows were changed...
291 if ( $affected > $this->expect
['maxAffected'] ) {
292 $this->reportExpectationViolated(
294 "[transaction $id writes to {$server} ({$db})]",
298 // Fill in the last non-query period...
299 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
301 $now = microtime( true );
302 $lastEnd = $lastQuery[2];
303 if ( ( $now - $lastEnd ) > $this->eventThreshold
) {
304 $this->dbTrxMethodTimes
[$name][] = [ '...delay...', $lastEnd, $now ];
307 // Check for any slow queries or non-query periods...
308 foreach ( $this->dbTrxMethodTimes
[$name] as $info ) {
309 $elapsed = ( $info[2] - $info[1] );
310 if ( $elapsed >= $this->dbLockThreshold
) {
317 foreach ( $this->dbTrxMethodTimes
[$name] as $i => $info ) {
318 list( $query, $sTime, $end ) = $info;
319 $trace .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
321 $this->logger
->info( "Sub-optimal transaction on DB(s) [{dbs}]: \n{trace}", [
322 'dbs' => implode( ', ', array_keys( $this->dbTrxHoldingLocks
[$name]['conns'] ) ),
326 unset( $this->dbTrxHoldingLocks
[$name] );
327 unset( $this->dbTrxMethodTimes
[$name] );
331 * @param string $expect
332 * @param string $query
333 * @param string|float|int $actual [optional]
335 protected function reportExpectationViolated( $expect, $query, $actual = null ) {
336 if ( $this->silenced
) {
340 $n = $this->expect
[$expect];
341 $by = $this->expectBy
[$expect];
342 $actual = ( $actual !== null ) ?
" (actual: $actual)" : "";
345 "Expectation ($expect <= $n) by $by not met$actual:\n$query\n" .
346 ( new RuntimeException() )->getTraceAsString()