Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / libs / rdbms / TransactionProfiler.php
blobbf5e299865aff72a3b2b1f58d6f78bd88d9ab9a5
1 <?php
2 /**
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
20 * @file
21 * @ingroup Profiler
22 * @author Aaron Schulz
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\NullLogger;
29 /**
30 * Helper class that detects high-contention DB queries via profiling calls
32 * This class is meant to work with an IDatabase object, which manages queries
34 * @since 1.24
36 class TransactionProfiler implements LoggerAwareInterface {
37 /** @var float Seconds */
38 protected $dbLockThreshold = 3.0;
39 /** @var float Seconds */
40 protected $eventThreshold = .25;
41 /** @var bool */
42 protected $silenced = false;
44 /** @var array transaction ID => (write start time, list of DBs involved) */
45 protected $dbTrxHoldingLocks = [];
46 /** @var array transaction ID => list of (query name, start time, end time) */
47 protected $dbTrxMethodTimes = [];
49 /** @var array */
50 protected $hits = [
51 'writes' => 0,
52 'queries' => 0,
53 'conns' => 0,
54 'masterConns' => 0
56 /** @var array */
57 protected $expect = [
58 'writes' => INF,
59 'queries' => INF,
60 'conns' => INF,
61 'masterConns' => INF,
62 'maxAffected' => INF,
63 'readQueryTime' => INF,
64 'writeQueryTime' => INF
66 /** @var array */
67 protected $expectBy = [];
69 /**
70 * @var LoggerInterface
72 private $logger;
74 public function __construct() {
75 $this->setLogger( new NullLogger() );
78 public function setLogger( LoggerInterface $logger ) {
79 $this->logger = $logger;
82 /**
83 * @param bool $value New value
84 * @return bool Old value
85 * @since 1.28
87 public function setSilenced( $value ) {
88 $old = $this->silenced;
89 $this->silenced = $value;
91 return $old;
94 /**
95 * Set performance expectations
97 * With conflicting expectations, the most narrow ones will be used
99 * @param string $event (writes,queries,conns,mConns)
100 * @param integer $value Maximum count of the event
101 * @param string $fname Caller
102 * @since 1.25
104 public function setExpectation( $event, $value, $fname ) {
105 $this->expect[$event] = isset( $this->expect[$event] )
106 ? min( $this->expect[$event], $value )
107 : $value;
108 if ( $this->expect[$event] == $value ) {
109 $this->expectBy[$event] = $fname;
114 * Set multiple performance expectations
116 * With conflicting expectations, the most narrow ones will be used
118 * @param array $expects Map of (event => limit)
119 * @param $fname
120 * @since 1.26
122 public function setExpectations( array $expects, $fname ) {
123 foreach ( $expects as $event => $value ) {
124 $this->setExpectation( $event, $value, $fname );
129 * Reset performance expectations and hit counters
131 * @since 1.25
133 public function resetExpectations() {
134 foreach ( $this->hits as &$val ) {
135 $val = 0;
137 unset( $val );
138 foreach ( $this->expect as &$val ) {
139 $val = INF;
141 unset( $val );
142 $this->expectBy = [];
146 * Mark a DB as having been connected to with a new handle
148 * Note that there can be multiple connections to a single DB.
150 * @param string $server DB server
151 * @param string $db DB name
152 * @param bool $isMaster
154 public function recordConnection( $server, $db, $isMaster ) {
155 // Report when too many connections happen...
156 if ( $this->hits['conns']++ == $this->expect['conns'] ) {
157 $this->reportExpectationViolated( 'conns', "[connect to $server ($db)]" );
159 if ( $isMaster && $this->hits['masterConns']++ == $this->expect['masterConns'] ) {
160 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
165 * Mark a DB as in a transaction with one or more writes pending
167 * Note that there can be multiple connections to a single DB.
169 * @param string $server DB server
170 * @param string $db DB name
171 * @param string $id ID string of transaction
173 public function transactionWritingIn( $server, $db, $id ) {
174 $name = "{$server} ({$db}) (TRX#$id)";
175 if ( isset( $this->dbTrxHoldingLocks[$name] ) ) {
176 $this->logger->info( "Nested transaction for '$name' - out of sync." );
178 $this->dbTrxHoldingLocks[$name] = [
179 'start' => microtime( true ),
180 'conns' => [], // all connections involved
182 $this->dbTrxMethodTimes[$name] = [];
184 foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
185 // Track all DBs in transactions for this transaction
186 $info['conns'][$name] = 1;
191 * Register the name and time of a method for slow DB trx detection
193 * This assumes that all queries are synchronous (non-overlapping)
195 * @param string $query Function name or generalized SQL
196 * @param float $sTime Starting UNIX wall time
197 * @param bool $isWrite Whether this is a write query
198 * @param integer $n Number of affected rows
200 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
201 $eTime = microtime( true );
202 $elapsed = ( $eTime - $sTime );
204 if ( $isWrite && $n > $this->expect['maxAffected'] ) {
205 $this->logger->info(
206 "Query affected $n row(s):\n" . $query . "\n" .
207 ( new RuntimeException() )->getTraceAsString() );
210 // Report when too many writes/queries happen...
211 if ( $this->hits['queries']++ == $this->expect['queries'] ) {
212 $this->reportExpectationViolated( 'queries', $query );
214 if ( $isWrite && $this->hits['writes']++ == $this->expect['writes'] ) {
215 $this->reportExpectationViolated( 'writes', $query );
217 // Report slow queries...
218 if ( !$isWrite && $elapsed > $this->expect['readQueryTime'] ) {
219 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
221 if ( $isWrite && $elapsed > $this->expect['writeQueryTime'] ) {
222 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
225 if ( !$this->dbTrxHoldingLocks ) {
226 // Short-circuit
227 return;
228 } elseif ( !$isWrite && $elapsed < $this->eventThreshold ) {
229 // Not an important query nor slow enough
230 return;
233 foreach ( $this->dbTrxHoldingLocks as $name => $info ) {
234 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
235 if ( $lastQuery ) {
236 // Additional query in the trx...
237 $lastEnd = $lastQuery[2];
238 if ( $sTime >= $lastEnd ) { // sanity check
239 if ( ( $sTime - $lastEnd ) > $this->eventThreshold ) {
240 // Add an entry representing the time spent doing non-queries
241 $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $sTime ];
243 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
245 } else {
246 // First query in the trx...
247 if ( $sTime >= $info['start'] ) { // sanity check
248 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
255 * Mark a DB as no longer in a transaction
257 * This will check if locks are possibly held for longer than
258 * needed and log any affected transactions to a special DB log.
259 * Note that there can be multiple connections to a single DB.
261 * @param string $server DB server
262 * @param string $db DB name
263 * @param string $id ID string of transaction
264 * @param float $writeTime Time spent in write queries
266 public function transactionWritingOut( $server, $db, $id, $writeTime = 0.0 ) {
267 $name = "{$server} ({$db}) (TRX#$id)";
268 if ( !isset( $this->dbTrxMethodTimes[$name] ) ) {
269 $this->logger->info( "Detected no transaction for '$name' - out of sync." );
270 return;
273 $slow = false;
275 // Warn if too much time was spend writing...
276 if ( $writeTime > $this->expect['writeQueryTime'] ) {
277 $this->reportExpectationViolated(
278 'writeQueryTime',
279 "[transaction $id writes to {$server} ({$db})]",
280 $writeTime
282 $slow = true;
284 // Fill in the last non-query period...
285 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
286 if ( $lastQuery ) {
287 $now = microtime( true );
288 $lastEnd = $lastQuery[2];
289 if ( ( $now - $lastEnd ) > $this->eventThreshold ) {
290 $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $now ];
293 // Check for any slow queries or non-query periods...
294 foreach ( $this->dbTrxMethodTimes[$name] as $info ) {
295 $elapsed = ( $info[2] - $info[1] );
296 if ( $elapsed >= $this->dbLockThreshold ) {
297 $slow = true;
298 break;
301 if ( $slow ) {
302 $trace = '';
303 foreach ( $this->dbTrxMethodTimes[$name] as $i => $info ) {
304 list( $query, $sTime, $end ) = $info;
305 $trace .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
307 $this->logger->info( "Sub-optimal transaction on DB(s) [{dbs}]: \n{trace}", [
308 'dbs' => implode( ', ', array_keys( $this->dbTrxHoldingLocks[$name]['conns'] ) ),
309 'trace' => $trace
310 ] );
312 unset( $this->dbTrxHoldingLocks[$name] );
313 unset( $this->dbTrxMethodTimes[$name] );
317 * @param string $expect
318 * @param string $query
319 * @param string|float|int $actual [optional]
321 protected function reportExpectationViolated( $expect, $query, $actual = null ) {
322 if ( $this->silenced ) {
323 return;
326 $n = $this->expect[$expect];
327 $by = $this->expectBy[$expect];
328 $actual = ( $actual !== null ) ? " (actual: $actual)" : "";
330 $this->logger->info(
331 "Expectation ($expect <= $n) by $by not met$actual:\n$query\n" .
332 ( new RuntimeException() )->getTraceAsString()