Merge "Add 3D filetype for STL files"
[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 namespace Wikimedia\Rdbms;
26
27 use Psr\Log\LoggerInterface;
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\NullLogger;
30 use RuntimeException;
31
32 /**
33 * Helper class that detects high-contention DB queries via profiling calls
34 *
35 * This class is meant to work with an IDatabase object, which manages queries
36 *
37 * @since 1.24
38 */
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;
46
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 = [];
51
52 /** @var array */
53 protected $hits = [
54 'writes' => 0,
55 'queries' => 0,
56 'conns' => 0,
57 'masterConns' => 0
58 ];
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
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 New 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 integer $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 $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( 'conns', "[connect to $server ($db)]" );
161 }
162 if ( $isMaster && $this->hits['masterConns']++ == $this->expect['masterConns'] ) {
163 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
164 }
165 }
166
167 /**
168 * Mark a DB as in a transaction with one or more writes pending
169 *
170 * Note that there can be multiple connections to a single DB.
171 *
172 * @param string $server DB server
173 * @param string $db DB name
174 * @param string $id ID string of transaction
175 */
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." );
180 }
181 $this->dbTrxHoldingLocks[$name] = [
182 'start' => microtime( true ),
183 'conns' => [], // all connections involved
184 ];
185 $this->dbTrxMethodTimes[$name] = [];
186
187 foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
188 // Track all DBs in transactions for this transaction
189 $info['conns'][$name] = 1;
190 }
191 }
192
193 /**
194 * Register the name and time of a method for slow DB trx detection
195 *
196 * This assumes that all queries are synchronous (non-overlapping)
197 *
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
202 */
203 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
204 $eTime = microtime( true );
205 $elapsed = ( $eTime - $sTime );
206
207 if ( $isWrite && $n > $this->expect['maxAffected'] ) {
208 $this->logger->info(
209 "Query affected $n row(s):\n" . $query . "\n" .
210 ( new RuntimeException() )->getTraceAsString() );
211 }
212
213 // Report when too many writes/queries happen...
214 if ( $this->hits['queries']++ == $this->expect['queries'] ) {
215 $this->reportExpectationViolated( 'queries', $query );
216 }
217 if ( $isWrite && $this->hits['writes']++ == $this->expect['writes'] ) {
218 $this->reportExpectationViolated( 'writes', $query );
219 }
220 // Report slow queries...
221 if ( !$isWrite && $elapsed > $this->expect['readQueryTime'] ) {
222 $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed );
223 }
224 if ( $isWrite && $elapsed > $this->expect['writeQueryTime'] ) {
225 $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed );
226 }
227
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;
234 }
235
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 ];
245 }
246 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
247 }
248 } else {
249 // First query in the trx...
250 if ( $sTime >= $info['start'] ) { // sanity check
251 $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
252 }
253 }
254 }
255 }
256
257 /**
258 * Mark a DB as no longer in a transaction
259 *
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.
263 *
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
268 * @param integer $affected Number of rows affected by writes
269 */
270 public function transactionWritingOut( $server, $db, $id, $writeTime = 0.0, $affected = 0 ) {
271 $name = "{$server} ({$db}) (TRX#$id)";
272 if ( !isset( $this->dbTrxMethodTimes[$name] ) ) {
273 $this->logger->info( "Detected no transaction for '$name' - out of sync." );
274 return;
275 }
276
277 $slow = false;
278
279 // Warn if too much time was spend writing...
280 if ( $writeTime > $this->expect['writeQueryTime'] ) {
281 $this->reportExpectationViolated(
282 'writeQueryTime',
283 "[transaction $id writes to {$server} ({$db})]",
284 $writeTime
285 );
286 $slow = true;
287 }
288 // Warn if too many rows were changed...
289 if ( $affected > $this->expect['maxAffected'] ) {
290 $this->reportExpectationViolated(
291 'maxAffected',
292 "[transaction $id writes to {$server} ({$db})]",
293 $affected
294 );
295 }
296 // Fill in the last non-query period...
297 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
298 if ( $lastQuery ) {
299 $now = microtime( true );
300 $lastEnd = $lastQuery[2];
301 if ( ( $now - $lastEnd ) > $this->eventThreshold ) {
302 $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $now ];
303 }
304 }
305 // Check for any slow queries or non-query periods...
306 foreach ( $this->dbTrxMethodTimes[$name] as $info ) {
307 $elapsed = ( $info[2] - $info[1] );
308 if ( $elapsed >= $this->dbLockThreshold ) {
309 $slow = true;
310 break;
311 }
312 }
313 if ( $slow ) {
314 $trace = '';
315 foreach ( $this->dbTrxMethodTimes[$name] as $i => $info ) {
316 list( $query, $sTime, $end ) = $info;
317 $trace .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
318 }
319 $this->logger->info( "Sub-optimal transaction on DB(s) [{dbs}]: \n{trace}", [
320 'dbs' => implode( ', ', array_keys( $this->dbTrxHoldingLocks[$name]['conns'] ) ),
321 'trace' => $trace
322 ] );
323 }
324 unset( $this->dbTrxHoldingLocks[$name] );
325 unset( $this->dbTrxMethodTimes[$name] );
326 }
327
328 /**
329 * @param string $expect
330 * @param string $query
331 * @param string|float|int $actual [optional]
332 */
333 protected function reportExpectationViolated( $expect, $query, $actual = null ) {
334 if ( $this->silenced ) {
335 return;
336 }
337
338 $n = $this->expect[$expect];
339 $by = $this->expectBy[$expect];
340 $actual = ( $actual !== null ) ? " (actual: $actual)" : "";
341
342 $this->logger->info(
343 "Expectation ($expect <= $n) by $by not met$actual:\n$query\n" .
344 ( new RuntimeException() )->getTraceAsString()
345 );
346 }
347 }