MediaWiki REL1_32
TransactionProfiler.php
Go to the documentation of this file.
1<?php
24namespace Wikimedia\Rdbms;
25
26use Psr\Log\LoggerInterface;
27use Psr\Log\LoggerAwareInterface;
28use Psr\Log\NullLogger;
29use RuntimeException;
30
38class TransactionProfiler implements LoggerAwareInterface {
40 protected $dbLockThreshold = 3.0;
42 protected $eventThreshold = 0.25;
44 protected $silenced = false;
45
47 protected $dbTrxHoldingLocks = [];
49 protected $dbTrxMethodTimes = [];
50
52 protected $hits = [
53 'writes' => 0,
54 'queries' => 0,
55 'conns' => 0,
56 'masterConns' => 0
57 ];
59 protected $expect = [
60 'writes' => INF,
61 'queries' => INF,
62 'conns' => INF,
63 'masterConns' => INF,
64 'maxAffected' => INF,
65 'readQueryRows' => INF,
66 'readQueryTime' => INF,
67 'writeQueryTime' => INF
68 ];
70 protected $expectBy = [];
71
75 private $logger;
76
77 public function __construct() {
78 $this->setLogger( new NullLogger() );
79 }
80
81 public function setLogger( LoggerInterface $logger ) {
82 $this->logger = $logger;
83 }
84
90 public function setSilenced( $value ) {
91 $old = $this->silenced;
92 $this->silenced = $value;
93
94 return $old;
95 }
96
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;
113 }
114 }
115
125 public function setExpectations( array $expects, $fname ) {
126 foreach ( $expects as $event => $value ) {
127 $this->setExpectation( $event, $value, $fname );
128 }
129 }
130
136 public function resetExpectations() {
137 foreach ( $this->hits as &$val ) {
138 $val = 0;
139 }
140 unset( $val );
141 foreach ( $this->expect as &$val ) {
142 $val = INF;
143 }
144 unset( $val );
145 $this->expectBy = [];
146 }
147
157 public function recordConnection( $server, $db, $isMaster ) {
158 // Report when too many connections happen...
159 if ( $this->hits['conns']++ >= $this->expect['conns'] ) {
161 'conns', "[connect to $server ($db)]", $this->hits['conns'] );
162 }
163 if ( $isMaster && $this->hits['masterConns']++ >= $this->expect['masterConns'] ) {
165 'masterConns', "[connect to $server ($db)]", $this->hits['masterConns'] );
166 }
167 }
168
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." );
182 }
183 $this->dbTrxHoldingLocks[$name] = [
184 'start' => microtime( true ),
185 'conns' => [], // all connections involved
186 ];
187 $this->dbTrxMethodTimes[$name] = [];
188
189 foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
190 // Track all DBs in transactions for this transaction
191 $info['conns'][$name] = 1;
192 }
193 }
194
205 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
206 $eTime = microtime( true );
207 $elapsed = ( $eTime - $sTime );
208
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() );
217 }
218
219 // Report when too many writes/queries happen...
220 if ( $this->hits['queries']++ >= $this->expect['queries'] ) {
221 $this->reportExpectationViolated( 'queries', $query, $this->hits['queries'] );
222 }
223 if ( $isWrite && $this->hits['writes']++ >= $this->expect['writes'] ) {
224 $this->reportExpectationViolated( 'writes', $query, $this->hits['writes'] );
225 }
226 // Report slow queries...
227 if ( !$isWrite && $elapsed > $this->expect['readQueryTime'] ) {
228 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
229 }
230 if ( $isWrite && $elapsed > $this->expect['writeQueryTime'] ) {
231 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
232 }
233
234 if ( !$this->dbTrxHoldingLocks ) {
235 // Short-circuit
236 return;
237 } elseif ( !$isWrite && $elapsed < $this->eventThreshold ) {
238 // Not an important query nor slow enough
239 return;
240 }
241
242 foreach ( $this->dbTrxHoldingLocks as $name => $info ) {
243 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
244 if ( $lastQuery ) {
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 ];
251 }
252 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
253 }
254 } else {
255 // First query in the trx...
256 if ( $sTime >= $info['start'] ) { // sanity check
257 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
258 }
259 }
260 }
261 }
262
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." );
280 return;
281 }
282
283 $slow = false;
284
285 // Warn if too much time was spend writing...
286 if ( $writeTime > $this->expect['writeQueryTime'] ) {
288 'writeQueryTime',
289 "[transaction $id writes to {$server} ({$db})]",
290 $writeTime
291 );
292 $slow = true;
293 }
294 // Warn if too many rows were changed...
295 if ( $affected > $this->expect['maxAffected'] ) {
297 'maxAffected',
298 "[transaction $id writes to {$server} ({$db})]",
299 $affected
300 );
301 }
302 // Fill in the last non-query period...
303 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
304 if ( $lastQuery ) {
305 $now = microtime( true );
306 $lastEnd = $lastQuery[2];
307 if ( ( $now - $lastEnd ) > $this->eventThreshold ) {
308 $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $now ];
309 }
310 }
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 ) {
315 $slow = true;
316 break;
317 }
318 }
319 if ( $slow ) {
320 $trace = '';
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 );
324 }
325 $this->logger->warning( "Sub-optimal transaction on DB(s) [{dbs}]: \n{trace}", [
326 'dbs' => implode( ', ', array_keys( $this->dbTrxHoldingLocks[$name]['conns'] ) ),
327 'trace' => $trace
328 ] );
329 }
330 unset( $this->dbTrxHoldingLocks[$name] );
331 unset( $this->dbTrxMethodTimes[$name] );
332 }
333
339 protected function reportExpectationViolated( $expect, $query, $actual ) {
340 if ( $this->silenced ) {
341 return;
342 }
343
344 $this->logger->warning(
345 "Expectation ({measure} <= {max}) by {by} not met (actual: {actual}):\n{query}\n" .
346 ( new RuntimeException() )->getTraceAsString(),
347 [
348 'measure' => $expect,
349 'max' => $this->expect[$expect],
350 'by' => $this->expectBy[$expect],
351 'actual' => $actual,
352 'query' => $query
353 ]
354 );
355 }
356}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:121
Helper class that detects high-contention DB queries via profiling calls.
setExpectation( $event, $value, $fname)
Set performance expectations.
resetExpectations()
Reset performance expectations and hit counters.
setExpectations(array $expects, $fname)
Set multiple performance expectations.
transactionWritingIn( $server, $db, $id)
Mark a DB as in a transaction with one or more writes pending.
recordConnection( $server, $db, $isMaster)
Mark a DB as having been connected to with a new handle.
array $dbTrxMethodTimes
transaction ID => list of (query name, start time, end time)
reportExpectationViolated( $expect, $query, $actual)
array $dbTrxHoldingLocks
transaction ID => (write start time, list of DBs involved)
recordQueryCompletion( $query, $sTime, $isWrite=false, $n=0)
Register the name and time of a method for slow DB trx detection.
transactionWritingOut( $server, $db, $id, $writeTime=0.0, $affected=0)
Mark a DB as no longer in a transaction.
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
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
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
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:1656
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:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))