Simplify profiler output class selection
[lhc/web/wiklou.git] / includes / profiler / Profiler.php
1 <?php
2 /**
3 * Base class for profiling.
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 * @defgroup Profiler Profiler
23 */
24
25 /**
26 * Profiler base class that defines the interface and some trivial
27 * functionality
28 *
29 * @ingroup Profiler
30 */
31 abstract class Profiler {
32 /** @var string|bool Profiler ID for bucketing data */
33 protected $profileID = false;
34 /** @var bool Whether MediaWiki is in a SkinTemplate output context */
35 protected $templated = false;
36 /** @var array All of the params passed from $wgProfiler */
37 protected $params = array();
38 /** @var IContextSource Current request context */
39 protected $context = null;
40 /** @var TransactionProfiler */
41 protected $trxProfiler;
42 /** @var Profiler */
43 private static $instance = null;
44
45 /**
46 * @param array $params
47 */
48 public function __construct( array $params ) {
49 if ( isset( $params['profileID'] ) ) {
50 $this->profileID = $params['profileID'];
51 }
52 $this->params = $params;
53 $this->trxProfiler = new TransactionProfiler();
54 }
55
56 /**
57 * Singleton
58 * @return Profiler
59 */
60 final public static function instance() {
61 if ( self::$instance === null ) {
62 global $wgProfiler, $wgProfileLimit;
63
64 $params = array(
65 'class' => 'ProfilerStub',
66 'sampling' => 1,
67 'threshold' => $wgProfileLimit,
68 'output' => array(),
69 );
70 if ( is_array( $wgProfiler ) ) {
71 $params = array_merge( $params, $wgProfiler );
72 }
73
74 $inSample = mt_rand( 0, $params['sampling'] - 1 ) === 0;
75 if ( PHP_SAPI === 'cli' || !$inSample ) {
76 $params['class'] = 'ProfilerStub';
77 }
78
79 if ( !is_array( $params['output'] ) ) {
80 $params['output'] = array( $params['output'] );
81 }
82
83 self::$instance = new $params['class']( $params );
84 }
85 return self::$instance;
86 }
87
88 /**
89 * Replace the current profiler with $profiler if no non-stub profiler is set
90 *
91 * @param Profiler $profiler
92 * @throws MWException
93 * @since 1.25
94 */
95 final public static function replaceStubInstance( Profiler $profiler ) {
96 if ( self::$instance && !( self::$instance instanceof ProfilerStub ) ) {
97 throw new MWException( 'Could not replace non-stub profiler instance.' );
98 } else {
99 self::$instance = $profiler;
100 }
101 }
102
103 /**
104 * @param string $id
105 */
106 public function setProfileID( $id ) {
107 $this->profileID = $id;
108 }
109
110 /**
111 * @return string
112 */
113 public function getProfileID() {
114 if ( $this->profileID === false ) {
115 return wfWikiID();
116 } else {
117 return $this->profileID;
118 }
119 }
120
121 /**
122 * Sets the context for this Profiler
123 *
124 * @param IContextSource $context
125 * @since 1.25
126 */
127 public function setContext( $context ) {
128 $this->context = $context;
129 }
130
131 /**
132 * Gets the context for this Profiler
133 *
134 * @return IContextSource
135 * @since 1.25
136 */
137 public function getContext() {
138 if ( $this->context ) {
139 return $this->context;
140 } else {
141 wfDebug( __METHOD__ . " called and \$context is null. " .
142 "Return RequestContext::getMain(); for sanity\n" );
143 return RequestContext::getMain();
144 }
145 }
146
147 // Kept BC for now, remove when possible
148 public function profileIn( $functionname ) {}
149 public function profileOut( $functionname ) {}
150
151 /**
152 * Mark the start of a custom profiling frame (e.g. DB queries).
153 * The frame ends when the result of this method falls out of scope.
154 *
155 * @param string $section
156 * @return ScopedCallback|null
157 * @since 1.25
158 */
159 abstract public function scopedProfileIn( $section );
160
161 /**
162 * @param ScopedCallback $section
163 */
164 public function scopedProfileOut( ScopedCallback &$section = null ) {
165 $section = null;
166 }
167
168 /**
169 * @return TransactionProfiler
170 * @since 1.25
171 */
172 public function getTransactionProfiler() {
173 return $this->trxProfiler;
174 }
175
176 /**
177 * Close opened profiling sections
178 */
179 abstract public function close();
180
181 /**
182 * Get all usable outputs.
183 *
184 * @throws MWException
185 * @return array Array of ProfilerOutput instances.
186 * @since 1.25
187 */
188 private function getOutputs() {
189 $outputs = array();
190 foreach ( $this->params['output'] as $outputType ) {
191 // The class may be specified as either the full class name (for
192 // example, 'ProfilerOutputUdp') or (for backward compatibility)
193 // the trailing portion of the class name (for example, 'udp').
194 $outputClass = strpos( $outputType, 'ProfilerOutput' ) === false
195 ? 'ProfilerOutput' . ucfirst( $outputType )
196 : $outputType;
197 if ( !class_exists( $outputClass ) ) {
198 throw new MWException( "'$outputType' is an invalid output type" );
199 }
200 $outputInstance = new $outputClass( $this, $this->params );
201 if ( $outputInstance->canUse() ) {
202 $outputs[] = $outputInstance;
203 }
204 }
205 return $outputs;
206 }
207
208 /**
209 * Log the data to some store or even the page output
210 *
211 * @since 1.25
212 */
213 public function logData() {
214 $request = $this->getContext()->getRequest();
215
216 $timeElapsed = $request->getElapsedTime();
217 $timeElapsedThreshold = $this->params['threshold'];
218 if ( $timeElapsed <= $timeElapsedThreshold ) {
219 return;
220 }
221
222 $outputs = $this->getOutputs();
223 if ( !$outputs ) {
224 return;
225 }
226
227 $stats = $this->getFunctionStats();
228 foreach ( $outputs as $output ) {
229 $output->log( $stats );
230 }
231 }
232
233 /**
234 * Get the content type sent out to the client.
235 * Used for profilers that output instead of store data.
236 * @return string
237 * @since 1.25
238 */
239 public function getContentType() {
240 foreach ( headers_list() as $header ) {
241 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
242 return $m[1];
243 }
244 }
245 return null;
246 }
247
248 /**
249 * Mark this call as templated or not
250 *
251 * @param bool $t
252 */
253 public function setTemplated( $t ) {
254 $this->templated = $t;
255 }
256
257 /**
258 * Was this call as templated or not
259 *
260 * @return bool
261 */
262 public function getTemplated() {
263 return $this->templated;
264 }
265
266 /**
267 * Get the aggregated inclusive profiling data for each method
268 *
269 * The percent time for each time is based on the current "total" time
270 * used is based on all methods so far. This method can therefore be
271 * called several times in between several profiling calls without the
272 * delays in usage of the profiler skewing the results. A "-total" entry
273 * is always included in the results.
274 *
275 * When a call chain involves a method invoked within itself, any
276 * entries for the cyclic invocation should be be demarked with "@".
277 * This makes filtering them out easier and follows the xhprof style.
278 *
279 * @return array List of method entries arrays, each having:
280 * - name : method name
281 * - calls : the number of invoking calls
282 * - real : real time ellapsed (ms)
283 * - %real : percent real time
284 * - cpu : CPU time ellapsed (ms)
285 * - %cpu : percent CPU time
286 * - memory : memory used (bytes)
287 * - %memory : percent memory used
288 * - min_real : min real time in a call (ms)
289 * - max_real : max real time in a call (ms)
290 * @since 1.25
291 */
292 abstract public function getFunctionStats();
293
294 /**
295 * Returns a profiling output to be stored in debug file
296 *
297 * @return string
298 */
299 abstract public function getOutput();
300 }