Added a separate error message for mkdir failures
[lhc/web/wiklou.git] / includes / profiler / 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 a DatabaseBase 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
42 /** @var array transaction ID => (write start time, list of DBs involved) */
43 protected $dbTrxHoldingLocks = array();
44 /** @var array transaction ID => list of (query name, start time, end time) */
45 protected $dbTrxMethodTimes = array();
46
47 /** @var array */
48 protected $hits = array(
49 'writes' => 0,
50 'queries' => 0,
51 'conns' => 0,
52 'masterConns' => 0
53 );
54 /** @var array */
55 protected $expect = array(
56 'writes' => INF,
57 'queries' => INF,
58 'conns' => INF,
59 'masterConns' => INF,
60 'maxAffected' => INF,
61 'readQueryTime' => INF,
62 'writeQueryTime' => INF
63 );
64 /** @var array */
65 protected $expectBy = array();
66
67 /**
68 * @var LoggerInterface
69 */
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
80 /**
81 * Set performance expectations
82 *
83 * With conflicting expectations, the most narrow ones will be used
84 *
85 * @param string $event (writes,queries,conns,mConns)
86 * @param integer $value Maximum count of the event
87 * @param string $fname Caller
88 * @since 1.25
89 */
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
99 /**
100 * Set multiple performance expectations
101 *
102 * With conflicting expectations, the most narrow ones will be used
103 *
104 * @param array $expects Map of (event => limit)
105 * @param $fname
106 * @since 1.26
107 */
108 public function setExpectations( array $expects, $fname ) {
109 foreach ( $expects as $event => $value ) {
110 $this->setExpectation( $event, $value, $fname );
111 }
112 }
113
114 /**
115 * Reset performance expectations and hit counters
116 *
117 * @since 1.25
118 */
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 = array();
129 }
130
131 /**
132 * Mark a DB as having been connected to with a new handle
133 *
134 * Note that there can be multiple connections to a single DB.
135 *
136 * @param string $server DB server
137 * @param string $db DB name
138 * @param bool $isMaster
139 */
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
150 /**
151 * Mark a DB as in a transaction with one or more writes pending
152 *
153 * Note that there can be multiple connections to a single DB.
154 *
155 * @param string $server DB server
156 * @param string $db DB name
157 * @param string $id ID string of transaction
158 */
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] = array(
165 'start' => microtime( true ),
166 'conns' => array(), // all connections involved
167 );
168 $this->dbTrxMethodTimes[$name] = array();
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
176 /**
177 * Register the name and time of a method for slow DB trx detection
178 *
179 * This assumes that all queries are synchronous (non-overlapping)
180 *
181 * @param string $query Function name or generalized SQL
182 * @param float $sTime Starting UNIX wall time
183 * @param bool $isWrite Whether this is a write query
184 * @param integer $n Number of affected rows
185 */
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][] = array( '...delay...', $lastEnd, $sTime );
227 }
228 $this->dbTrxMethodTimes[$name][] = array( $query, $sTime, $eTime );
229 }
230 } else {
231 // First query in the trx...
232 if ( $sTime >= $info['start'] ) { // sanity check
233 $this->dbTrxMethodTimes[$name][] = array( $query, $sTime, $eTime );
234 }
235 }
236 }
237 }
238
239 /**
240 * Mark a DB as no longer in a transaction
241 *
242 * This will check if locks are possibly held for longer than
243 * needed and log any affected transactions to a special DB log.
244 * Note that there can be multiple connections to a single DB.
245 *
246 * @param string $server DB server
247 * @param string $db DB name
248 * @param string $id ID string of transaction
249 * @param float $writeTime Time spent in write queries
250 */
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'] ) {
262 $this->reportExpectationViolated(
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][] = array( '...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
299 /**
300 * @param string $expect
301 * @param string $query
302 * @param string|float|int $actual [optional]
303 */
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 }