Merge "Revert "Use display name in category page subheadings if provided""
[lhc/web/wiklou.git] / includes / libs / rdbms / TransactionProfiler.php
1 <?php
2 /**
3 * Transaction profiling for contention
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Profiler
22 * @author Aaron Schulz
23 */
24
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\NullLogger;
28
29 /**
30 * Helper class that detects high-contention DB queries via profiling calls
31 *
32 * This class is meant to work with an IDatabase object, which manages queries
33 *
34 * @since 1.24
35 */
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;
43
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 = [];
48
49 /** @var array */
50 protected $hits = [
51 'writes' => 0,
52 'queries' => 0,
53 'conns' => 0,
54 'masterConns' => 0
55 ];
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
65 ];
66 /** @var array */
67 protected $expectBy = [];
68
69 /**
70 * @var LoggerInterface
71 */
72 private $logger;
73
74 public function __construct() {
75 $this->setLogger( new NullLogger() );
76 }
77
78 public function setLogger( LoggerInterface $logger ) {
79 $this->logger = $logger;
80 }
81
82 /**
83 * @param bool $value New value
84 * @return bool Old value
85 * @since 1.28
86 */
87 public function setSilenced( $value ) {
88 $old = $this->silenced;
89 $this->silenced = $value;
90
91 return $old;
92 }
93
94 /**
95 * Set performance expectations
96 *
97 * With conflicting expectations, the most narrow ones will be used
98 *
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
103 */
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;
110 }
111 }
112
113 /**
114 * Set multiple performance expectations
115 *
116 * With conflicting expectations, the most narrow ones will be used
117 *
118 * @param array $expects Map of (event => limit)
119 * @param $fname
120 * @since 1.26
121 */
122 public function setExpectations( array $expects, $fname ) {
123 foreach ( $expects as $event => $value ) {
124 $this->setExpectation( $event, $value, $fname );
125 }
126 }
127
128 /**
129 * Reset performance expectations and hit counters
130 *
131 * @since 1.25
132 */
133 public function resetExpectations() {
134 foreach ( $this->hits as &$val ) {
135 $val = 0;
136 }
137 unset( $val );
138 foreach ( $this->expect as &$val ) {
139 $val = INF;
140 }
141 unset( $val );
142 $this->expectBy = [];
143 }
144
145 /**
146 * Mark a DB as having been connected to with a new handle
147 *
148 * Note that there can be multiple connections to a single DB.
149 *
150 * @param string $server DB server
151 * @param string $db DB name
152 * @param bool $isMaster
153 */
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)]" );
158 }
159 if ( $isMaster && $this->hits['masterConns']++ == $this->expect['masterConns'] ) {
160 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
161 }
162 }
163
164 /**
165 * Mark a DB as in a transaction with one or more writes pending
166 *
167 * Note that there can be multiple connections to a single DB.
168 *
169 * @param string $server DB server
170 * @param string $db DB name
171 * @param string $id ID string of transaction
172 */
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." );
177 }
178 $this->dbTrxHoldingLocks[$name] = [
179 'start' => microtime( true ),
180 'conns' => [], // all connections involved
181 ];
182 $this->dbTrxMethodTimes[$name] = [];
183
184 foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
185 // Track all DBs in transactions for this transaction
186 $info['conns'][$name] = 1;
187 }
188 }
189
190 /**
191 * Register the name and time of a method for slow DB trx detection
192 *
193 * This assumes that all queries are synchronous (non-overlapping)
194 *
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
199 */
200 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
201 $eTime = microtime( true );
202 $elapsed = ( $eTime - $sTime );
203
204 if ( $isWrite && $n > $this->expect['maxAffected'] ) {
205 $this->logger->info(
206 "Query affected $n row(s):\n" . $query . "\n" .
207 ( new RuntimeException() )->getTraceAsString() );
208 }
209
210 // Report when too many writes/queries happen...
211 if ( $this->hits['queries']++ == $this->expect['queries'] ) {
212 $this->reportExpectationViolated( 'queries', $query );
213 }
214 if ( $isWrite && $this->hits['writes']++ == $this->expect['writes'] ) {
215 $this->reportExpectationViolated( 'writes', $query );
216 }
217 // Report slow queries...
218 if ( !$isWrite && $elapsed > $this->expect['readQueryTime'] ) {
219 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
220 }
221 if ( $isWrite && $elapsed > $this->expect['writeQueryTime'] ) {
222 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
223 }
224
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;
231 }
232
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 ];
242 }
243 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
244 }
245 } else {
246 // First query in the trx...
247 if ( $sTime >= $info['start'] ) { // sanity check
248 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
249 }
250 }
251 }
252 }
253
254 /**
255 * Mark a DB as no longer in a transaction
256 *
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.
260 *
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
265 */
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;
271 }
272
273 $slow = false;
274
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
281 );
282 $slow = true;
283 }
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 ];
291 }
292 }
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;
299 }
300 }
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 );
306 }
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 ] );
311 }
312 unset( $this->dbTrxHoldingLocks[$name] );
313 unset( $this->dbTrxMethodTimes[$name] );
314 }
315
316 /**
317 * @param string $expect
318 * @param string $query
319 * @param string|float|int $actual [optional]
320 */
321 protected function reportExpectationViolated( $expect, $query, $actual = null ) {
322 if ( $this->silenced ) {
323 return;
324 }
325
326 $n = $this->expect[$expect];
327 $by = $this->expectBy[$expect];
328 $actual = ( $actual !== null ) ? " (actual: $actual)" : "";
329
330 $this->logger->info(
331 "Expectation ($expect <= $n) by $by not met$actual:\n$query\n" .
332 ( new RuntimeException() )->getTraceAsString()
333 );
334 }
335 }