Move mssql class to /libs
[mediawiki.git] / includes / libs / rdbms / TransactionProfiler.php
blob5d3534ffaa4138935e36b1b2e43ed7602614e908
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 namespace Wikimedia\Rdbms;
27 use Psr\Log\LoggerInterface;
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\NullLogger;
30 use RuntimeException;
32 /**
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
37 * @since 1.24
39 class TransactionProfiler implements LoggerAwareInterface {
40 /** @var float Seconds */
41 protected $dbLockThreshold = 3.0;
42 /** @var float Seconds */
43 protected $eventThreshold = .25;
44 /** @var bool */
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 = [];
52 /** @var array */
53 protected $hits = [
54 'writes' => 0,
55 'queries' => 0,
56 'conns' => 0,
57 'masterConns' => 0
59 /** @var array */
60 protected $expect = [
61 'writes' => INF,
62 'queries' => INF,
63 'conns' => INF,
64 'masterConns' => INF,
65 'maxAffected' => INF,
66 'readQueryTime' => INF,
67 'writeQueryTime' => INF
69 /** @var array */
70 protected $expectBy = [];
72 /**
73 * @var LoggerInterface
75 private $logger;
77 public function __construct() {
78 $this->setLogger( new NullLogger() );
81 public function setLogger( LoggerInterface $logger ) {
82 $this->logger = $logger;
85 /**
86 * @param bool $value New value
87 * @return bool Old value
88 * @since 1.28
90 public function setSilenced( $value ) {
91 $old = $this->silenced;
92 $this->silenced = $value;
94 return $old;
97 /**
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
105 * @since 1.25
107 public function setExpectation( $event, $value, $fname ) {
108 $this->expect[$event] = isset( $this->expect[$event] )
109 ? min( $this->expect[$event], $value )
110 : $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 $fname
123 * @since 1.26
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
134 * @since 1.25
136 public function resetExpectations() {
137 foreach ( $this->hits as &$val ) {
138 $val = 0;
140 unset( $val );
141 foreach ( $this->expect as &$val ) {
142 $val = INF;
144 unset( $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( 'conns', "[connect to $server ($db)]" );
162 if ( $isMaster && $this->hits['masterConns']++ == $this->expect['masterConns'] ) {
163 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
168 * Mark a DB as in a transaction with one or more writes pending
170 * Note that there can be multiple connections to a single DB.
172 * @param string $server DB server
173 * @param string $db DB name
174 * @param string $id ID string of transaction
176 public function transactionWritingIn( $server, $db, $id ) {
177 $name = "{$server} ({$db}) (TRX#$id)";
178 if ( isset( $this->dbTrxHoldingLocks[$name] ) ) {
179 $this->logger->info( "Nested transaction for '$name' - out of sync." );
181 $this->dbTrxHoldingLocks[$name] = [
182 'start' => microtime( true ),
183 'conns' => [], // all connections involved
185 $this->dbTrxMethodTimes[$name] = [];
187 foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
188 // Track all DBs in transactions for this transaction
189 $info['conns'][$name] = 1;
194 * Register the name and time of a method for slow DB trx detection
196 * This assumes that all queries are synchronous (non-overlapping)
198 * @param string $query Function name or generalized SQL
199 * @param float $sTime Starting UNIX wall time
200 * @param bool $isWrite Whether this is a write query
201 * @param integer $n Number of affected rows
203 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
204 $eTime = microtime( true );
205 $elapsed = ( $eTime - $sTime );
207 if ( $isWrite && $n > $this->expect['maxAffected'] ) {
208 $this->logger->info(
209 "Query affected $n row(s):\n" . $query . "\n" .
210 ( new RuntimeException() )->getTraceAsString() );
213 // Report when too many writes/queries happen...
214 if ( $this->hits['queries']++ == $this->expect['queries'] ) {
215 $this->reportExpectationViolated( 'queries', $query );
217 if ( $isWrite && $this->hits['writes']++ == $this->expect['writes'] ) {
218 $this->reportExpectationViolated( 'writes', $query );
220 // Report slow queries...
221 if ( !$isWrite && $elapsed > $this->expect['readQueryTime'] ) {
222 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
224 if ( $isWrite && $elapsed > $this->expect['writeQueryTime'] ) {
225 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
228 if ( !$this->dbTrxHoldingLocks ) {
229 // Short-circuit
230 return;
231 } elseif ( !$isWrite && $elapsed < $this->eventThreshold ) {
232 // Not an important query nor slow enough
233 return;
236 foreach ( $this->dbTrxHoldingLocks as $name => $info ) {
237 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
238 if ( $lastQuery ) {
239 // Additional query in the trx...
240 $lastEnd = $lastQuery[2];
241 if ( $sTime >= $lastEnd ) { // sanity check
242 if ( ( $sTime - $lastEnd ) > $this->eventThreshold ) {
243 // Add an entry representing the time spent doing non-queries
244 $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $sTime ];
246 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
248 } else {
249 // First query in the trx...
250 if ( $sTime >= $info['start'] ) { // sanity check
251 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
258 * Mark a DB as no longer in a transaction
260 * This will check if locks are possibly held for longer than
261 * needed and log any affected transactions to a special DB log.
262 * Note that there can be multiple connections to a single DB.
264 * @param string $server DB server
265 * @param string $db DB name
266 * @param string $id ID string of transaction
267 * @param float $writeTime Time spent in write queries
269 public function transactionWritingOut( $server, $db, $id, $writeTime = 0.0 ) {
270 $name = "{$server} ({$db}) (TRX#$id)";
271 if ( !isset( $this->dbTrxMethodTimes[$name] ) ) {
272 $this->logger->info( "Detected no transaction for '$name' - out of sync." );
273 return;
276 $slow = false;
278 // Warn if too much time was spend writing...
279 if ( $writeTime > $this->expect['writeQueryTime'] ) {
280 $this->reportExpectationViolated(
281 'writeQueryTime',
282 "[transaction $id writes to {$server} ({$db})]",
283 $writeTime
285 $slow = true;
287 // Fill in the last non-query period...
288 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
289 if ( $lastQuery ) {
290 $now = microtime( true );
291 $lastEnd = $lastQuery[2];
292 if ( ( $now - $lastEnd ) > $this->eventThreshold ) {
293 $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $now ];
296 // Check for any slow queries or non-query periods...
297 foreach ( $this->dbTrxMethodTimes[$name] as $info ) {
298 $elapsed = ( $info[2] - $info[1] );
299 if ( $elapsed >= $this->dbLockThreshold ) {
300 $slow = true;
301 break;
304 if ( $slow ) {
305 $trace = '';
306 foreach ( $this->dbTrxMethodTimes[$name] as $i => $info ) {
307 list( $query, $sTime, $end ) = $info;
308 $trace .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
310 $this->logger->info( "Sub-optimal transaction on DB(s) [{dbs}]: \n{trace}", [
311 'dbs' => implode( ', ', array_keys( $this->dbTrxHoldingLocks[$name]['conns'] ) ),
312 'trace' => $trace
313 ] );
315 unset( $this->dbTrxHoldingLocks[$name] );
316 unset( $this->dbTrxMethodTimes[$name] );
320 * @param string $expect
321 * @param string $query
322 * @param string|float|int $actual [optional]
324 protected function reportExpectationViolated( $expect, $query, $actual = null ) {
325 if ( $this->silenced ) {
326 return;
329 $n = $this->expect[$expect];
330 $by = $this->expectBy[$expect];
331 $actual = ( $actual !== null ) ? " (actual: $actual)" : "";
333 $this->logger->info(
334 "Expectation ($expect <= $n) by $by not met$actual:\n$query\n" .
335 ( new RuntimeException() )->getTraceAsString()