Debian Codegraph @

includes/profiler/Profiler.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\WikiMap\WikiMap;
23 use Psr\Log\LoggerInterface;
24 use Wikimedia\Rdbms\TransactionProfiler;
25
26 /**
27 * @defgroup Profiler Profiler
28 */
29
30 /**
31 * Profiler base class that defines the interface and some shared
32 * functionality.
33 *
34 * @ingroup Profiler
35 */
36 abstract class Profiler {
37 /** @var string|false Profiler ID for bucketing data */
38 protected $profileID = false;
39 /** @var array All of the params passed from $wgProfiler */
40 protected $params = [];
41 /** @var TransactionProfiler */
42 protected $trxProfiler;
43 /** @var LoggerInterface */
44 protected $logger;
45 /** @var bool */
46 private $allowOutput = false;
47
48 /** @var Profiler */
49 private static $instance = null;
50
51 /**
52 * @param array $params See $wgProfiler.
53 */
54 public function __construct( array $params ) {
55 if ( isset( $params['profileID'] ) ) {
56 $this->profileID = $params['profileID'];
57 }
58 $this->params = $params;
59 $this->trxProfiler = new TransactionProfiler();
60 $this->logger = LoggerFactory::getInstance( 'profiler' );
61 }
62
63 /**
64 * @internal For use by Setup.php
65 * @param array $profilerConf Value from $wgProfiler
66 */
67 final public static function init( array $profilerConf ): void {
68 $params = $profilerConf + [
69 'class' => ProfilerStub::class,
70 'sampling' => 1,
71 'threshold' => 0.0,
72 'output' => [],
73 'cliEnable' => false,
74 ];
75
76 // Avoid global func wfIsCLI() during setup
77 $isCLI = ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
78 $inSample = $params['sampling'] === 1 || mt_rand( 1, $params['sampling'] ) === 1;
79 if (
80 !$inSample ||
81 // On CLI, profiling is disabled by default, and can be explicitly enabled
82 // via the `--profiler` option, which MediaWiki\Maintenance\MaintenanceRunner::setup
83 // translates into 'cliEnable'.
84 // See also $wgProfiler docs.
85 //
86 // For this to work, Setup.php must call Profiler::init() after handling of
87 // MW_FINAL_SETUP_CALLBACK, which is what doMaintenance.php uses to call
88 // MaintenanceRunner::setup.
89 ( $isCLI && !$params['cliEnable'] )
90 ) {
91 $params['class'] = ProfilerStub::class;
92 }
93
94 if ( !is_array( $params['output'] ) ) {
95 $params['output'] = [ $params['output'] ];
96 }
97
98 self::$instance = new $params['class']( $params );
99 }
100
101 /**
102 * @return Profiler
103 */
104 final public static function instance() {
105 if ( !self::$instance ) {
106 trigger_error( 'Called Profiler::instance before settings are loaded', E_USER_WARNING );
107 self::init( [] );
108 }
109
110 return self::$instance;
111 }
112
113 /**
114 * @deprecated since 1.41, unused. Can override this base class.
115 * @param string $id
116 */
117 public function setProfileID( $id ) {
118 wfDeprecated( __METHOD__, '1.41' );
119 $this->profileID = $id;
120 }
121
122 /**
123 * @return string
124 */
125 public function getProfileID() {
126 if ( $this->profileID === false ) {
127 return WikiMap::getCurrentWikiDbDomain()->getId();
128 } else {
129 return $this->profileID;
130 }
131 }
132
133 /**
134 * Mark the start of a custom profiling frame (e.g. DB queries).
135 * The frame ends when the result of this method falls out of scope.
136 *
137 * @param string $section
138 * @since 1.25
139 */
140 abstract public function scopedProfileIn( $section ): ?SectionProfileCallback;
141
142 /**
143 * @param SectionProfileCallback|null &$section
144 */
145 public function scopedProfileOut( ?SectionProfileCallback &$section = null ) {
146 $section = null;
147 }
148
149 /**
150 * @return TransactionProfiler
151 * @since 1.25
152 */
153 public function getTransactionProfiler() {
154 return $this->trxProfiler;
155 }
156
157 /**
158 * Close opened profiling sections
159 */
160 abstract public function close();
161
162 /**
163 * Get all usable outputs.
164 *
165 * @return ProfilerOutput[]
166 * @since 1.25
167 */
168 private function getOutputs() {
169 $outputs = [];
170 foreach ( $this->params['output'] as $outputType ) {
171 // The class may be specified as either the full class name (for
172 // example, 'ProfilerOutputStats') or (for backward compatibility)
173 // the trailing portion of the class name (for example, 'stats').
174 $outputClass = strpos( $outputType, 'ProfilerOutput' ) === false
175 ? 'ProfilerOutput' . ucfirst( $outputType )
176 : $outputType;
177 if ( !class_exists( $outputClass ) ) {
178 throw new UnexpectedValueException( "'$outputType' is an invalid output type" );
179 }
180 $outputInstance = new $outputClass( $this, $this->params );
181 if ( $outputInstance->canUse() ) {
182 $outputs[] = $outputInstance;
183 }
184 }
185 return $outputs;
186 }
187
188 /**
189 * Log data to all the applicable backing stores
190 *
191 * This logs the profiling data to the backing store for each configured ProfilerOutput
192 * instance. It also logs any request data for the TransactionProfiler instance.
193 *
194 * @since 1.25
195 */
196 public function logData() {
197 if ( $this->params['threshold'] > 0.0 ) {
198 // Note, this is also valid for CLI processes.
199 $timeElapsed = microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'];
200 if ( $timeElapsed <= $this->params['threshold'] ) {
201 return;
202 }
203 }
204
205 $outputs = [];
206 foreach ( $this->getOutputs() as $output ) {
207 if ( !$output->logsToOutput() ) {
208 $outputs[] = $output;
209 }
210 }
211
212 if ( $outputs ) {
213 $stats = $this->getFunctionStats();
214 foreach ( $outputs as $output ) {
215 $output->log( $stats );
216 }
217 }
218 }
219
220 /**
221 * Log the data to the script/request output for all ProfilerOutput instances that do so
222 *
223 * @since 1.26
224 */
225 public function logDataPageOutputOnly() {
226 if ( !$this->allowOutput ) {
227 return;
228 }
229
230 $outputs = [];
231 foreach ( $this->getOutputs() as $output ) {
232 if ( $output->logsToOutput() ) {
233 $outputs[] = $output;
234 }
235 }
236
237 if ( $outputs ) {
238 $stats = $this->getFunctionStats();
239 foreach ( $outputs as $output ) {
240 $output->log( $stats );
241 }
242 }
243 }
244
245 /**
246 * Get the Content-Type for deciding how to format appended profile output.
247 *
248 * Disabled by default. Enable via setAllowOutput().
249 *
250 * @see ProfilerOutputText
251 * @since 1.25
252 * @return string|null Returns null if disabled or no Content-Type found.
253 */
254 public function getContentType() {
255 if ( $this->allowOutput ) {
256 foreach ( headers_list() as $header ) {
257 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
258 return $m[1];
259 }
260 }
261 }
262 return null;
263 }
264
265 /**
266 * Enable appending profiles to standard output.
267 *
268 * @since 1.34
269 */
270 public function setAllowOutput() {
271 $this->allowOutput = true;
272 }
273
274 /**
275 * Whether appending profiles is allowed.
276 *
277 * @deprecated since 1.41. Unused.
278 *
279 * @since 1.34
280 * @return bool
281 */
282 public function getAllowOutput() {
283 wfDeprecated( __METHOD__, '1.41' );
284 return $this->allowOutput;
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 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 }