Merge "Allow to set stub read buffer size for TextPassDumper"
[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 /**
26 * Helper class that detects high-contention DB queries via profiling calls
27 *
28 * This class is meant to work with a DatabaseBase object, which manages queries
29 *
30 * @since 1.24
31 */
32 class TransactionProfiler {
33 /** @var float Seconds */
34 protected $dbLockThreshold = 3.0;
35 /** @var float Seconds */
36 protected $eventThreshold = .25;
37
38 /** @var array transaction ID => (write start time, list of DBs involved) */
39 protected $dbTrxHoldingLocks = array();
40 /** @var array transaction ID => list of (query name, start time, end time) */
41 protected $dbTrxMethodTimes = array();
42
43 /** @var array */
44 protected $hits = array(
45 'writes' => 0,
46 'queries' => 0,
47 'conns' => 0,
48 'masterConns' => 0
49 );
50 /** @var array */
51 protected $expect = array(
52 'writes' => INF,
53 'queries' => INF,
54 'conns' => INF,
55 'masterConns' => INF,
56 'maxAffected' => INF
57 );
58 /** @var array */
59 protected $expectBy = array();
60
61 /**
62 * Set performance expectations
63 *
64 * With conflicting expect, the most specific ones will be used
65 *
66 * @param string $event (writes,queries,conns,mConns)
67 * @param integer $value Maximum count of the event
68 * @param string $fname Caller
69 * @since 1.25
70 */
71 public function setExpectation( $event, $value, $fname ) {
72 $this->expect[$event] = isset( $this->expect[$event] )
73 ? min( $this->expect[$event], $value )
74 : $value;
75 if ( $this->expect[$event] == $value ) {
76 $this->expectBy[$event] = $fname;
77 }
78 }
79
80 /**
81 * Reset performance expectations and hit counters
82 *
83 * @since 1.25
84 */
85 public function resetExpectations() {
86 foreach ( $this->hits as &$val ) {
87 $val = 0;
88 }
89 unset( $val );
90 foreach ( $this->expect as &$val ) {
91 $val = INF;
92 }
93 unset( $val );
94 $this->expectBy = array();
95 }
96
97 /**
98 * Mark a DB as having been connected to with a new handle
99 *
100 * Note that there can be multiple connections to a single DB.
101 *
102 * @param string $server DB server
103 * @param string $db DB name
104 * @param bool $isMaster
105 */
106 public function recordConnection( $server, $db, $isMaster ) {
107 // Report when too many connections happen...
108 if ( $this->hits['conns']++ == $this->expect['conns'] ) {
109 $this->reportExpectationViolated( 'conns', "[connect to $server ($db)]" );
110 }
111 if ( $isMaster && $this->hits['masterConns']++ == $this->expect['masterConns'] ) {
112 $this->reportExpectationViolated( 'masterConns', "[connect to $server ($db)]" );
113 }
114 }
115
116 /**
117 * Mark a DB as in a transaction with one or more writes pending
118 *
119 * Note that there can be multiple connections to a single DB.
120 *
121 * @param string $server DB server
122 * @param string $db DB name
123 * @param string $id ID string of transaction
124 */
125 public function transactionWritingIn( $server, $db, $id ) {
126 $name = "{$server} ({$db}) (TRX#$id)";
127 if ( isset( $this->dbTrxHoldingLocks[$name] ) ) {
128 wfDebugLog( 'DBPerformance', "Nested transaction for '$name' - out of sync." );
129 }
130 $this->dbTrxHoldingLocks[$name] = array(
131 'start' => microtime( true ),
132 'conns' => array(), // all connections involved
133 );
134 $this->dbTrxMethodTimes[$name] = array();
135
136 foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
137 // Track all DBs in transactions for this transaction
138 $info['conns'][$name] = 1;
139 }
140 }
141
142 /**
143 * Register the name and time of a method for slow DB trx detection
144 *
145 * This assumes that all queries are synchronous (non-overlapping)
146 *
147 * @param string $query Function name or generalized SQL
148 * @param float $sTime Starting UNIX wall time
149 * @param bool $isWrite Whether this is a write query
150 * @param integer $n Number of affected rows
151 */
152 public function recordQueryCompletion( $query, $sTime, $isWrite = false, $n = 0 ) {
153 $eTime = microtime( true );
154 $elapsed = ( $eTime - $sTime );
155
156 if ( $isWrite && $n > $this->expect['maxAffected'] ) {
157 wfDebugLog( 'DBPerformance',
158 "Query affected $n row(s):\n" . $query . "\n" . wfBacktrace( true ) );
159 }
160
161 // Report when too many writes/queries happen...
162 if ( $this->hits['queries']++ == $this->expect['queries'] ) {
163 $this->reportExpectationViolated( 'queries', $query );
164 }
165 if ( $isWrite && $this->hits['writes']++ == $this->expect['writes'] ) {
166 $this->reportExpectationViolated( 'writes', $query );
167 }
168
169 if ( !$this->dbTrxHoldingLocks ) {
170 // Short-circuit
171 return;
172 } elseif ( !$isWrite && $elapsed < $this->eventThreshold ) {
173 // Not an important query nor slow enough
174 return;
175 }
176
177 foreach ( $this->dbTrxHoldingLocks as $name => $info ) {
178 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
179 if ( $lastQuery ) {
180 // Additional query in the trx...
181 $lastEnd = $lastQuery[2];
182 if ( $sTime >= $lastEnd ) { // sanity check
183 if ( ( $sTime - $lastEnd ) > $this->eventThreshold ) {
184 // Add an entry representing the time spent doing non-queries
185 $this->dbTrxMethodTimes[$name][] = array( '...delay...', $lastEnd, $sTime );
186 }
187 $this->dbTrxMethodTimes[$name][] = array( $query, $sTime, $eTime );
188 }
189 } else {
190 // First query in the trx...
191 if ( $sTime >= $info['start'] ) { // sanity check
192 $this->dbTrxMethodTimes[$name][] = array( $query, $sTime, $eTime );
193 }
194 }
195 }
196 }
197
198 /**
199 * Mark a DB as no longer in a transaction
200 *
201 * This will check if locks are possibly held for longer than
202 * needed and log any affected transactions to a special DB log.
203 * Note that there can be multiple connections to a single DB.
204 *
205 * @param string $server DB server
206 * @param string $db DB name
207 * @param string $id ID string of transaction
208 */
209 public function transactionWritingOut( $server, $db, $id ) {
210 $name = "{$server} ({$db}) (TRX#$id)";
211 if ( !isset( $this->dbTrxMethodTimes[$name] ) ) {
212 wfDebugLog( 'DBPerformance', "Detected no transaction for '$name' - out of sync." );
213 return;
214 }
215 // Fill in the last non-query period...
216 $lastQuery = end( $this->dbTrxMethodTimes[$name] );
217 if ( $lastQuery ) {
218 $now = microtime( true );
219 $lastEnd = $lastQuery[2];
220 if ( ( $now - $lastEnd ) > $this->eventThreshold ) {
221 $this->dbTrxMethodTimes[$name][] = array( '...delay...', $lastEnd, $now );
222 }
223 }
224 // Check for any slow queries or non-query periods...
225 $slow = false;
226 foreach ( $this->dbTrxMethodTimes[$name] as $info ) {
227 $elapsed = ( $info[2] - $info[1] );
228 if ( $elapsed >= $this->dbLockThreshold ) {
229 $slow = true;
230 break;
231 }
232 }
233 if ( $slow ) {
234 $dbs = implode( ', ', array_keys( $this->dbTrxHoldingLocks[$name]['conns'] ) );
235 $msg = "Sub-optimal transaction on DB(s) [{$dbs}]:\n";
236 foreach ( $this->dbTrxMethodTimes[$name] as $i => $info ) {
237 list( $query, $sTime, $end ) = $info;
238 $msg .= sprintf( "%d\t%.6f\t%s\n", $i, ( $end - $sTime ), $query );
239 }
240 wfDebugLog( 'DBPerformance', $msg );
241 }
242 unset( $this->dbTrxHoldingLocks[$name] );
243 unset( $this->dbTrxMethodTimes[$name] );
244 }
245
246 /**
247 * @param string $expect
248 * @param string $query
249 */
250 protected function reportExpectationViolated( $expect, $query ) {
251 $n = $this->expect[$expect];
252 $by = $this->expectBy[$expect];
253 wfDebugLog( 'DBPerformance',
254 "Expectation ($expect <= $n) by $by not met:\n$query\n" . wfBacktrace( true ) );
255 }
256 }