MediaWiki  1.27.2
TransactionProfiler.php
Go to the documentation of this file.
1 <?php
28 
36 class TransactionProfiler implements LoggerAwareInterface {
38  protected $dbLockThreshold = 3.0;
40  protected $eventThreshold = .25;
41 
43  protected $dbTrxHoldingLocks = [];
45  protected $dbTrxMethodTimes = [];
46 
48  protected $hits = [
49  'writes' => 0,
50  'queries' => 0,
51  'conns' => 0,
52  'masterConns' => 0
53  ];
55  protected $expect = [
56  'writes' => INF,
57  'queries' => INF,
58  'conns' => INF,
59  'masterConns' => INF,
60  'maxAffected' => INF,
61  'readQueryTime' => INF,
62  'writeQueryTime' => INF
63  ];
65  protected $expectBy = [];
66 
70  private $logger;
71 
72  public function __construct() {
73  $this->setLogger( new NullLogger() );
74  }
75 
76  public function setLogger( LoggerInterface $logger ) {
77  $this->logger = $logger;
78  }
79 
90  public function setExpectation( $event, $value, $fname ) {
91  $this->expect[$event] = isset( $this->expect[$event] )
92  ? min( $this->expect[$event], $value )
93  : $value;
94  if ( $this->expect[$event] == $value ) {
95  $this->expectBy[$event] = $fname;
96  }
97  }
98 
108  public function setExpectations( array $expects, $fname ) {
109  foreach ( $expects as $event => $value ) {
110  $this->setExpectation( $event, $value, $fname );
111  }
112  }
113 
119  public function resetExpectations() {
120  foreach ( $this->hits as &$val ) {
121  $val = 0;
122  }
123  unset( $val );
124  foreach ( $this->expect as &$val ) {
125  $val = INF;
126  }
127  unset( $val );
128  $this->expectBy = [];
129  }
130 
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)]" );
144  }
145  if ( $isMaster && $this->hits['masterConns']++ == $this->expect['masterConns'] ) {
146  $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
147  }
148  }
149 
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." );
163  }
164  $this->dbTrxHoldingLocks[$name] = [
165  'start' => microtime( true ),
166  'conns' => [], // all connections involved
167  ];
168  $this->dbTrxMethodTimes[$name] = [];
169 
170  foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
171  // Track all DBs in transactions for this transaction
172  $info['conns'][$name] = 1;
173  }
174  }
175 
186  public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
187  $eTime = microtime( true );
188  $elapsed = ( $eTime - $sTime );
189 
190  if ( $isWrite && $n > $this->expect['maxAffected'] ) {
191  $this->logger->info( "Query affected $n row(s):\n" . $query . "\n" .
192  wfBacktrace( true ) );
193  }
194 
195  // Report when too many writes/queries happen...
196  if ( $this->hits['queries']++ == $this->expect['queries'] ) {
197  $this->reportExpectationViolated( 'queries', $query );
198  }
199  if ( $isWrite && $this->hits['writes']++ == $this->expect['writes'] ) {
200  $this->reportExpectationViolated( 'writes', $query );
201  }
202  // Report slow queries...
203  if ( !$isWrite && $elapsed > $this->expect['readQueryTime'] ) {
204  $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
205  }
206  if ( $isWrite && $elapsed > $this->expect['writeQueryTime'] ) {
207  $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
208  }
209 
210  if ( !$this->dbTrxHoldingLocks ) {
211  // Short-circuit
212  return;
213  } elseif ( !$isWrite && $elapsed < $this->eventThreshold ) {
214  // Not an important query nor slow enough
215  return;
216  }
217 
218  foreach ( $this->dbTrxHoldingLocks as $name => $info ) {
219  $lastQuery = end( $this->dbTrxMethodTimes[$name] );
220  if ( $lastQuery ) {
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 ];
227  }
228  $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
229  }
230  } else {
231  // First query in the trx...
232  if ( $sTime >= $info['start'] ) { // sanity check
233  $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
234  }
235  }
236  }
237  }
238 
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." );
255  return;
256  }
257 
258  $slow = false;
259 
260  // Warn if too much time was spend writing...
261  if ( $writeTime > $this->expect['writeQueryTime'] ) {
263  'writeQueryTime',
264  "[transaction $id writes to {$server} ({$db})]",
265  $writeTime
266  );
267  $slow = true;
268  }
269  // Fill in the last non-query period...
270  $lastQuery = end( $this->dbTrxMethodTimes[$name] );
271  if ( $lastQuery ) {
272  $now = microtime( true );
273  $lastEnd = $lastQuery[2];
274  if ( ( $now - $lastEnd ) > $this->eventThreshold ) {
275  $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $now ];
276  }
277  }
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 ) {
282  $slow = true;
283  break;
284  }
285  }
286  if ( $slow ) {
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 );
292  }
293  $this->logger->info( $msg );
294  }
295  unset( $this->dbTrxHoldingLocks[$name] );
296  unset( $this->dbTrxMethodTimes[$name] );
297  }
298 
304  protected function reportExpectationViolated( $expect, $query, $actual = null ) {
305  $n = $this->expect[$expect];
306  $by = $this->expectBy[$expect];
307  $actual = ( $actual !== null ) ? " (actual: $actual)" : "";
308 
309  $this->logger->info(
310  "Expectation ($expect <= $n) by $by not met$actual:\n$query\n" .
311  wfBacktrace( true )
312  );
313  }
314 }
array $dbTrxMethodTimes
transaction ID => list of (query name, start time, end time)
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
the array() calling protocol came about after MediaWiki 1.4rc1.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1418
float $dbLockThreshold
Seconds.
reportExpectationViolated($expect, $query, $actual=null)
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
array $dbTrxHoldingLocks
transaction ID => (write start time, list of DBs involved)
float $eventThreshold
Seconds.
wfBacktrace($raw=null)
Get a debug backtrace as a string.
$value
array array array $expectBy
setExpectations(array $expects, $fname)
Set multiple performance expectations.
Helper class that detects high-contention DB queries via profiling calls.
resetExpectations()
Reset performance expectations and hit counters.
setExpectation($event, $value, $fname)
Set performance expectations.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
setLogger(LoggerInterface $logger)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:35
transactionWritingOut($server, $db, $id, $writeTime=0.0)
Mark a DB as no longer in a transaction.
recordConnection($server, $db, $isMaster)
Mark a DB as having been connected to with a new handle.
transactionWritingIn($server, $db, $id)
Mark a DB as in a transaction with one or more writes pending.
recordQueryCompletion($query, $sTime, $isWrite=false, $n=0)
Register the name and time of a method for slow DB trx detection.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310