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