summaryrefslogtreecommitdiff
path: root/includes/profiler/Profiler.php
blob: 418b5d48b6692792fdb359c2c66e3c43e1f1765f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
<?php
/**
 * Base class and functions for profiling.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Profiler
 * @defgroup Profiler Profiler
 */

/**
 * Get system resource usage of current request context.
 * Invokes the getrusage(2) system call, requesting RUSAGE_SELF if on PHP5
 * or RUSAGE_THREAD if on HHVM. Returns false if getrusage is not available.
 *
 * @since 1.24
 * @return array|bool Resource usage data or false if no data available.
 */
function wfGetRusage() {
	if ( !function_exists( 'getrusage' ) ) {
		return false;
	} elseif ( defined ( 'HHVM_VERSION' ) ) {
		return getrusage( 2 /* RUSAGE_THREAD */ );
	} else {
		return getrusage( 0 /* RUSAGE_SELF */ );
	}
}

/**
 * Begin profiling of a function
 * @param string $functionname Name of the function we will profile
 */
function wfProfileIn( $functionname ) {
	if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
		Profiler::instance();
	}
	if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
		Profiler::$__instance->profileIn( $functionname );
	}
}

/**
 * Stop profiling of a function
 * @param string $functionname Name of the function we have profiled
 */
function wfProfileOut( $functionname = 'missing' ) {
	if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
		Profiler::instance();
	}
	if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
		Profiler::$__instance->profileOut( $functionname );
	}
}

/**
 * Class for handling function-scope profiling
 *
 * @since 1.22
 */
class ProfileSection {
	protected $name; // string; method name
	protected $enabled = false; // boolean; whether profiling is enabled

	/**
	 * Begin profiling of a function and return an object that ends profiling of
	 * the function when that object leaves scope. As long as the object is not
	 * specifically linked to other objects, it will fall out of scope at the same
	 * moment that the function to be profiled terminates.
	 *
	 * This is typically called like:
	 * <code>$section = new ProfileSection( __METHOD__ );</code>
	 *
	 * @param string $name Name of the function to profile
	 */
	public function __construct( $name ) {
		$this->name = $name;
		if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
			Profiler::instance();
		}
		if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
			$this->enabled = true;
			Profiler::$__instance->profileIn( $this->name );
		}
	}

	function __destruct() {
		if ( $this->enabled ) {
			Profiler::$__instance->profileOut( $this->name );
		}
	}
}

/**
 * Profiler base class that defines the interface and some trivial functionality
 *
 * @ingroup Profiler
 */
abstract class Profiler {
	/** @var string|bool Profiler ID for bucketing data */
	protected $mProfileID = false;
	/** @var bool Whether MediaWiki is in a SkinTemplate output context */
	protected $mTemplated = false;

	/** @var TransactionProfiler */
	protected $trxProfiler;

	// @codingStandardsIgnoreStart PSR2.Classes.PropertyDeclaration.Underscore
	/** @var Profiler Do not call this outside Profiler and ProfileSection */
	public static $__instance = null;
	// @codingStandardsIgnoreEnd

	/**
	 * @param array $params
	 */
	public function __construct( array $params ) {
		if ( isset( $params['profileID'] ) ) {
			$this->mProfileID = $params['profileID'];
		}
		$this->trxProfiler = new TransactionProfiler();
	}

	/**
	 * Singleton
	 * @return Profiler
	 */
	final public static function instance() {
		if ( self::$__instance === null ) {
			global $wgProfiler;
			if ( is_array( $wgProfiler ) ) {
				if ( !isset( $wgProfiler['class'] ) ) {
					$class = 'ProfilerStub';
				} elseif ( $wgProfiler['class'] === 'Profiler' ) {
					$class = 'ProfilerStub'; // b/c; don't explode
				} else {
					$class = $wgProfiler['class'];
				}
				self::$__instance = new $class( $wgProfiler );
			} elseif ( $wgProfiler instanceof Profiler ) {
				self::$__instance = $wgProfiler; // back-compat
			} else {
				self::$__instance = new ProfilerStub( array() );
			}
		}
		return self::$__instance;
	}

	/**
	 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
	 * @param Profiler $p
	 */
	final public static function setInstance( Profiler $p ) {
		self::$__instance = $p;
	}

	/**
	 * Return whether this a stub profiler
	 *
	 * @return bool
	 */
	abstract public function isStub();

	/**
	 * Return whether this profiler stores data
	 *
	 * Called by Parser::braceSubstitution. If true, the parser will not
	 * generate per-title profiling sections, to avoid overloading the
	 * profiling data collector.
	 *
	 * @see Profiler::logData()
	 * @return bool
	 */
	abstract public function isPersistent();

	/**
	 * @param string $id
	 */
	public function setProfileID( $id ) {
		$this->mProfileID = $id;
	}

	/**
	 * @return string
	 */
	public function getProfileID() {
		if ( $this->mProfileID === false ) {
			return wfWikiID();
		} else {
			return $this->mProfileID;
		}
	}

	/**
	 * Called by wfProfieIn()
	 *
	 * @param string $functionname
	 */
	abstract public function profileIn( $functionname );

	/**
	 * Called by wfProfieOut()
	 *
	 * @param string $functionname
	 */
	abstract public function profileOut( $functionname );

	/**
	 * Mark a DB as in a transaction with one or more writes pending
	 *
	 * Note that there can be multiple connections to a single DB.
	 *
	 * @param string $server DB server
	 * @param string $db DB name
	 * @param string $id Resource ID string of connection
	 */
	public function transactionWritingIn( $server, $db, $id = '' ) {
		$this->trxProfiler->transactionWritingIn( $server, $db, $id );
	}

	/**
	 * Mark a DB as no longer in a transaction
	 *
	 * This will check if locks are possibly held for longer than
	 * needed and log any affected transactions to a special DB log.
	 * Note that there can be multiple connections to a single DB.
	 *
	 * @param string $server DB server
	 * @param string $db DB name
	 * @param string $id Resource ID string of connection
	 */
	public function transactionWritingOut( $server, $db, $id = '' ) {
		$this->trxProfiler->transactionWritingOut( $server, $db, $id );
	}

	/**
	 * Close opened profiling sections
	 */
	abstract public function close();

	/**
	 * Log the data to some store or even the page output
	 */
	abstract public function logData();

	/**
	 * Mark this call as templated or not
	 *
	 * @param bool $t
	 */
	public function setTemplated( $t ) {
		$this->mTemplated = $t;
	}

	/**
	 * Returns a profiling output to be stored in debug file
	 *
	 * @return string
	 */
	abstract public function getOutput();

	/**
	 * @return array
	 */
	abstract public function getRawData();

	/**
	 * Get the initial time of the request, based either on $wgRequestTime or
	 * $wgRUstart. Will return null if not able to find data.
	 *
	 * @param string|bool $metric Metric to use, with the following possibilities:
	 *   - user: User CPU time (without system calls)
	 *   - cpu: Total CPU time (user and system calls)
	 *   - wall (or any other string): elapsed time
	 *   - false (default): will fall back to default metric
	 * @return float|null
	 */
	protected function getTime( $metric = 'wall' ) {
		if ( $metric === 'cpu' || $metric === 'user' ) {
			$ru = wfGetRusage();
			if ( !$ru ) {
				return 0;
			}
			$time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
			if ( $metric === 'cpu' ) {
				# This is the time of system calls, added to the user time
				# it gives the total CPU time
				$time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
			}
			return $time;
		} else {
			return microtime( true );
		}
	}

	/**
	 * Get the initial time of the request, based either on $wgRequestTime or
	 * $wgRUstart. Will return null if not able to find data.
	 *
	 * @param string|bool $metric Metric to use, with the following possibilities:
	 *   - user: User CPU time (without system calls)
	 *   - cpu: Total CPU time (user and system calls)
	 *   - wall (or any other string): elapsed time
	 *   - false (default): will fall back to default metric
	 * @return float|null
	 */
	protected function getInitialTime( $metric = 'wall' ) {
		global $wgRequestTime, $wgRUstart;

		if ( $metric === 'cpu' || $metric === 'user' ) {
			if ( !count( $wgRUstart ) ) {
				return null;
			}

			$time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
			if ( $metric === 'cpu' ) {
				# This is the time of system calls, added to the user time
				# it gives the total CPU time
				$time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
			}
			return $time;
		} else {
			if ( empty( $wgRequestTime ) ) {
				return null;
			} else {
				return $wgRequestTime;
			}
		}
	}

	/**
	 * Add an entry in the debug log file
	 *
	 * @param string $s String to output
	 */
	protected function debug( $s ) {
		if ( function_exists( 'wfDebug' ) ) {
			wfDebug( $s );
		}
	}

	/**
	 * Add an entry in the debug log group
	 *
	 * @param string $group Group to send the message to
	 * @param string $s String to output
	 */
	protected function debugGroup( $group, $s ) {
		if ( function_exists( 'wfDebugLog' ) ) {
			wfDebugLog( $group, $s );
		}
	}
}

/**
 * Helper class that detects high-contention DB queries via profiling calls
 *
 * This class is meant to work with a Profiler, as the later already knows
 * when methods start and finish (which may take place during transactions).
 *
 * @since 1.24
 */
class TransactionProfiler {
	/** @var float Seconds */
	protected $mDBLockThreshold = 3.0;
	/** @var array DB/server name => (active trx count, time, DBs involved) */
	protected $mDBTrxHoldingLocks = array();
	/** @var array DB/server name => list of (function name, elapsed time) */
	protected $mDBTrxMethodTimes = array();

	/**
	 * Mark a DB as in a transaction with one or more writes pending
	 *
	 * Note that there can be multiple connections to a single DB.
	 *
	 * @param string $server DB server
	 * @param string $db DB name
	 * @param string $id ID string of transaction
	 */
	public function transactionWritingIn( $server, $db, $id ) {
		$name = "{$server} ({$db}) (TRX#$id)";
		if ( isset( $this->mDBTrxHoldingLocks[$name] ) ) {
			wfDebugLog( 'DBPerformance', "Nested transaction for '$name' - out of sync." );
		}
		$this->mDBTrxHoldingLocks[$name] =
			array( 'start' => microtime( true ), 'conns' => array() );
		$this->mDBTrxMethodTimes[$name] = array();

		foreach ( $this->mDBTrxHoldingLocks as $name => &$info ) {
			$info['conns'][$name] = 1; // track all DBs in transactions for this transaction
		}
	}

	/**
	 * Register the name and time of a method for slow DB trx detection
	 *
	 * This method is only to be called by the Profiler class as methods finish
	 *
	 * @param string $method Function name
	 * @param float $realtime Wal time ellapsed
	 */
	public function recordFunctionCompletion( $method, $realtime ) {
		if ( !$this->mDBTrxHoldingLocks ) {
			return; // short-circuit
		// @todo hardcoded check is a tad janky (what about FOR UPDATE?)
		} elseif ( !preg_match( '/^query-m: (?!SELECT)/', $method )
			&& $realtime < $this->mDBLockThreshold
		) {
			return; // not a DB master query nor slow enough
		}
		$now = microtime( true );
		foreach ( $this->mDBTrxHoldingLocks as $name => $info ) {
			// Hacky check to exclude entries from before the first TRX write
			if ( ( $now - $realtime ) >= $info['start'] ) {
				$this->mDBTrxMethodTimes[$name][] = array( $method, $realtime );
			}
		}
	}

	/**
	 * Mark a DB as no longer in a transaction
	 *
	 * This will check if locks are possibly held for longer than
	 * needed and log any affected transactions to a special DB log.
	 * Note that there can be multiple connections to a single DB.
	 *
	 * @param string $server DB server
	 * @param string $db DB name
	 * @param string $id ID string of transaction
	 */
	public function transactionWritingOut( $server, $db, $id ) {
		$name = "{$server} ({$db}) (TRX#$id)";
		if ( !isset( $this->mDBTrxMethodTimes[$name] ) ) {
			wfDebugLog( 'DBPerformance', "Detected no transaction for '$name' - out of sync." );
			return;
		}
		$slow = false;
		foreach ( $this->mDBTrxMethodTimes[$name] as $info ) {
			$realtime = $info[1];
			if ( $realtime >= $this->mDBLockThreshold ) {
				$slow = true;
				break;
			}
		}
		if ( $slow ) {
			$dbs = implode( ', ', array_keys( $this->mDBTrxHoldingLocks[$name]['conns'] ) );
			$msg = "Sub-optimal transaction on DB(s) [{$dbs}]:\n";
			foreach ( $this->mDBTrxMethodTimes[$name] as $i => $info ) {
				list( $method, $realtime ) = $info;
				$msg .= sprintf( "%d\t%.6f\t%s\n", $i, $realtime, $method );
			}
			wfDebugLog( 'DBPerformance', $msg );
		}
		unset( $this->mDBTrxHoldingLocks[$name] );
		unset( $this->mDBTrxMethodTimes[$name] );
	}
}