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
24 namespace Wikimedia\Rdbms
;
26 use Psr\Log\LoggerInterface
;
27 use Psr\Log\LoggerAwareInterface
;
28 use Psr\Log\NullLogger
;
32 * Helper class that detects high-contention DB queries via profiling calls
34 * This class is meant to work with an IDatabase object, which manages queries
38 class TransactionProfiler
implements LoggerAwareInterface
{
39 /** @var float Seconds */
40 protected $dbLockThreshold = 3.0;
41 /** @var float Seconds */
42 protected $eventThreshold = 0.25;
44 protected $silenced = false;
46 /** @var array transaction ID => (write start time, list of DBs involved) */
47 protected $dbTrxHoldingLocks = [];
48 /** @var array transaction ID => list of (query name, start time, end time) */
49 protected $dbTrxMethodTimes = [];
65 'readQueryRows' => INF
,
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;
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 int $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)
122 * @param string $fname
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
->warning( "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 int $n Number of affected/read 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'] ) {
210 $this->logger
->warning(
211 "Query affected $n row(s):\n" . $query . "\n" .
212 ( new RuntimeException() )->getTraceAsString() );
213 } elseif ( !$isWrite && $n > $this->expect
['readQueryRows'] ) {
214 $this->logger
->warning(
215 "Query returned $n row(s):\n" . $query . "\n" .
216 ( new RuntimeException() )->getTraceAsString() );
219 // Report when too many writes/queries happen...
220 if ( $this->hits
['queries']++
>= $this->expect
['queries'] ) {
221 $this->reportExpectationViolated( 'queries', $query, $this->hits
['queries'] );
223 if ( $isWrite && $this->hits
['writes']++
>= $this->expect
['writes'] ) {
224 $this->reportExpectationViolated( 'writes', $query, $this->hits
['writes'] );
226 // Report slow queries...
227 if ( !$isWrite && $elapsed > $this->expect
['readQueryTime'] ) {
228 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
230 if ( $isWrite && $elapsed > $this->expect
['writeQueryTime'] ) {
231 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
234 if ( !$this->dbTrxHoldingLocks
) {
237 } elseif ( !$isWrite && $elapsed < $this->eventThreshold
) {
238 // Not an important query nor slow enough
242 foreach ( $this->dbTrxHoldingLocks
as $name => $info ) {
243 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
245 // Additional query in the trx...
246 $lastEnd = $lastQuery[2];
247 if ( $sTime >= $lastEnd ) { // sanity check
248 if ( ( $sTime - $lastEnd ) > $this->eventThreshold
) {
249 // Add an entry representing the time spent doing non-queries
250 $this->dbTrxMethodTimes
[$name][] = [ '...delay...', $lastEnd, $sTime ];
252 $this->dbTrxMethodTimes
[$name][] = [ $query, $sTime, $eTime ];
255 // First query in the trx...
256 if ( $sTime >= $info['start'] ) { // sanity check
257 $this->dbTrxMethodTimes
[$name][] = [ $query, $sTime, $eTime ];
264 * Mark a DB as no longer in a transaction
266 * This will check if locks are possibly held for longer than
267 * needed and log any affected transactions to a special DB log.
268 * Note that there can be multiple connections to a single DB.
270 * @param string $server DB server
271 * @param string $db DB name
272 * @param string $id ID string of transaction
273 * @param float $writeTime Time spent in write queries
274 * @param int $affected Number of rows affected by writes
276 public function transactionWritingOut( $server, $db, $id, $writeTime = 0.0, $affected = 0 ) {
277 $name = "{$server} ({$db}) (TRX#$id)";
278 if ( !isset( $this->dbTrxMethodTimes
[$name] ) ) {
279 $this->logger
->warning( "Detected no transaction for '$name' - out of sync." );
285 // Warn if too much time was spend writing...
286 if ( $writeTime > $this->expect
['writeQueryTime'] ) {
287 $this->reportExpectationViolated(
289 "[transaction $id writes to {$server} ({$db})]",
294 // Warn if too many rows were changed...
295 if ( $affected > $this->expect
['maxAffected'] ) {
296 $this->reportExpectationViolated(
298 "[transaction $id writes to {$server} ({$db})]",
302 // Fill in the last non-query period...
303 $lastQuery = end( $this->dbTrxMethodTimes
[$name] );
305 $now = microtime( true );
306 $lastEnd = $lastQuery[2];
307 if ( ( $now - $lastEnd ) > $this->eventThreshold
) {
308 $this->dbTrxMethodTimes
[$name][] = [ '...delay...', $lastEnd, $now ];
311 // Check for any slow queries or non-query periods...
312 foreach ( $this->dbTrxMethodTimes
[$name] as $info ) {
313 $elapsed = ( $info[2] - $info[1] );
314 if ( $elapsed >= $this->dbLockThreshold
) {
321 foreach ( $this->dbTrxMethodTimes
[$name] as $i => $info ) {
322 list( $query, $sTime, $end ) = $info;
323 $trace .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
325 $this->logger
->warning( "Sub-optimal transaction on DB(s) [{dbs}]: \n{trace}", [
326 'dbs' => implode( ', ', array_keys( $this->dbTrxHoldingLocks
[$name]['conns'] ) ),
330 unset( $this->dbTrxHoldingLocks
[$name] );
331 unset( $this->dbTrxMethodTimes
[$name] );
335 * @param string $expect
336 * @param string $query
337 * @param string|float|int $actual
339 protected function reportExpectationViolated( $expect, $query, $actual ) {
340 if ( $this->silenced
) {
344 $this->logger
->warning(
345 "Expectation ({measure} <= {max}) by {by} not met (actual: {actual}):\n{query}\n" .
346 ( new RuntimeException() )->getTraceAsString(),
348 'measure' => $expect,
349 'max' => $this->expect
[$expect],
350 'by' => $this->expectBy
[$expect],