Merge "test: Assert that API generators have unique prefixes"
[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 */
23
24 namespace Wikimedia\Rdbms;
25
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\LoggerAwareInterface;
28 use Psr\Log\NullLogger;
29 use RuntimeException;
30
31 /**
32 * Helper class that detects high-contention DB queries via profiling calls
33 *
34 * This class is meant to work with an IDatabase object, which manages queries
35 *
36 * @since 1.24
37 */
38 class TransactionProfiler implements LoggerAwareInterface {
39 /** @var float Seconds */
40 protected $dbLockThreshold = 3.0;
41 /** @var float Seconds */
42 protected $eventThreshold = 0.25;
43 /** @var bool */
44 protected $silenced = false;
45
46 /** @var array transaction ID => (write start time, list of DBs involved) */
47 protected $dbTrxHoldingLocks = [];
48 /** @var array transaction ID => list of (query name, start time, end time) */
49 protected $dbTrxMethodTimes = [];
50
51 /** @var array */
52 protected $hits = [
53 'writes' => 0,
54 'queries' => 0,
55 'conns' => 0,
56 'masterConns' => 0
57 ];
58 /** @var array */
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 ];
69 /** @var array */
70 protected $expectBy = [];
71
72 /**
73 * @var LoggerInterface
74 */
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
85 /**
86 * @param bool $value
87 * @return bool Old value
88 * @since 1.28
89 */
90 public function setSilenced( $value ) {
91 $old = $this->silenced;
92 $this->silenced = $value;
93
94 return $old;
95 }
96
97 /**
98 * Set performance expectations
99 *
100 * With conflicting expectations, the most narrow ones will be used
101 *
102 * @param string $event (writes,queries,conns,mConns)
103 * @param int $value Maximum count of the event
104 * @param string $fname Caller
105 * @since 1.25
106 */
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
116 /**
117 * Set multiple performance expectations
118 *
119 * With conflicting expectations, the most narrow ones will be used
120 *
121 * @param array $expects Map of (event => limit)
122 * @param string $fname
123 * @since 1.26
124 */
125 public function setExpectations( array $expects, $fname ) {
126 foreach ( $expects as $event => $value ) {
127 $this->setExpectation( $event, $value, $fname );
128 }
129 }
130
131 /**
132 * Reset performance expectations and hit counters
133 *
134 * @since 1.25
135 */
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
148 /**
149 * Mark a DB as having been connected to with a new handle
150 *
151 * Note that there can be multiple connections to a single DB.
152 *
153 * @param string $server DB server
154 * @param string $db DB name
155 * @param bool $isMaster
156 */
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(
161 'conns', "[connect to $server ($db)]", $this->hits['conns'] );
162 }
163 if ( $isMaster && $this->hits['masterConns']++ >= $this->expect['masterConns'] ) {
164 $this->reportExpectationViolated(
165 'masterConns', "[connect to $server ($db)]", $this->hits['masterConns'] );
166 }
167 }
168
169 /**
170 * Mark a DB as in a transaction with one or more writes pending
171 *
172 * Note that there can be multiple connections to a single DB.
173 *
174 * @param string $server DB server
175 * @param string $db DB name
176 * @param string $id ID string of transaction
177 */
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
195 /**
196 * Register the name and time of a method for slow DB trx detection
197 *
198 * This assumes that all queries are synchronous (non-overlapping)
199 *
200 * @param string $query Function name or generalized SQL
201 * @param float $sTime Starting UNIX wall time
202 * @param bool $isWrite Whether this is a write query
203 * @param int $n Number of affected/read rows
204 */
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
263 /**
264 * Mark a DB as no longer in a transaction
265 *
266 * This will check if locks are possibly held for longer than
267 * needed and log any affected transactions to a special DB log.
268 * Note that there can be multiple connections to a single DB.
269 *
270 * @param string $server DB server
271 * @param string $db DB name
272 * @param string $id ID string of transaction
273 * @param float $writeTime Time spent in write queries
274 * @param int $affected Number of rows affected by writes
275 */
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'] ) {
287 $this->reportExpectationViolated(
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'] ) {
296 $this->reportExpectationViolated(
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
334 /**
335 * @param string $expect
336 * @param string $query
337 * @param string|float|int $actual
338 */
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 }