Merge "Use adaptive CDN TTLs for page views"
[mediawiki.git] / includes / exception / MWExceptionHandler.php
blob736cb06a21942149232a59b530b20d1595abd206
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.
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.
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
18 * @file
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\MediaWikiServices;
24 /**
25 * Handler class for MWExceptions
26 * @ingroup Exception
28 class MWExceptionHandler {
30 /**
31 * @var string $reservedMemory
33 protected static $reservedMemory;
34 /**
35 * @var array $fatalErrorTypes
37 protected static $fatalErrorTypes = [
38 E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
39 /* HHVM's FATAL_ERROR level */ 16777217,
41 /**
42 * @var bool $handledFatalCallback
44 protected static $handledFatalCallback = false;
46 /**
47 * Install handlers with PHP.
49 public static function installHandler() {
50 set_exception_handler( 'MWExceptionHandler::handleException' );
51 set_error_handler( 'MWExceptionHandler::handleError' );
53 // Reserve 16k of memory so we can report OOM fatals
54 self::$reservedMemory = str_repeat( ' ', 16384 );
55 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
58 /**
59 * Report an exception to the user
60 * @param Exception|Throwable $e
62 protected static function report( $e ) {
63 try {
64 // Try and show the exception prettily, with the normal skin infrastructure
65 if ( $e instanceof MWException ) {
66 // Delegate to MWException until all subclasses are handled by
67 // MWExceptionRenderer and MWException::report() has been
68 // removed.
69 $e->report();
70 } else {
71 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
73 } catch ( Exception $e2 ) {
74 // Exception occurred from within exception handler
75 // Show a simpler message for the original exception,
76 // don't try to invoke report()
77 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
81 /**
82 * If there are any open database transactions, roll them back and log
83 * the stack trace of the exception that should have been caught so the
84 * transaction could be aborted properly.
86 * @since 1.23
87 * @param Exception|Throwable $e
89 public static function rollbackMasterChangesAndLog( $e ) {
90 $services = MediaWikiServices::getInstance();
91 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
92 return; // T147599
95 $lbFactory = $services->getDBLoadBalancerFactory();
96 if ( $lbFactory->hasMasterChanges() ) {
97 $logger = LoggerFactory::getInstance( 'Bug56269' );
98 $logger->warning(
99 'Exception thrown with an uncommited database transaction: ' .
100 self::getLogMessage( $e ),
101 self::getLogContext( $e )
104 $lbFactory->rollbackMasterChanges( __METHOD__ );
108 * Exception handler which simulates the appropriate catch() handling:
110 * try {
111 * ...
112 * } catch ( Exception $e ) {
113 * $e->report();
114 * } catch ( Exception $e ) {
115 * echo $e->__toString();
118 * @since 1.25
119 * @param Exception|Throwable $e
121 public static function handleException( $e ) {
122 try {
123 // Rollback DBs to avoid transaction notices. This may fail
124 // to rollback some DB due to connection issues or exceptions.
125 // However, any sane DB driver will rollback implicitly anyway.
126 self::rollbackMasterChangesAndLog( $e );
127 } catch ( DBError $e2 ) {
128 // If the DB is unreacheable, rollback() will throw an error
129 // and the error report() method might need messages from the DB,
130 // which would result in an exception loop. PHP may escalate such
131 // errors to "Exception thrown without a stack frame" fatals, but
132 // it's better to be explicit here.
133 self::logException( $e2 );
136 self::logException( $e );
137 self::report( $e );
139 // Exit value should be nonzero for the benefit of shell jobs
140 exit( 1 );
144 * Handler for set_error_handler() callback notifications.
146 * Receive a callback from the interpreter for a raised error, create an
147 * ErrorException, and log the exception to the 'error' logging
148 * channel(s). If the raised error is a fatal error type (only under HHVM)
149 * delegate to handleFatalError() instead.
151 * @since 1.25
153 * @param int $level Error level raised
154 * @param string $message
155 * @param string $file
156 * @param int $line
157 * @return bool
159 * @see logError()
161 public static function handleError(
162 $level, $message, $file = null, $line = null
164 if ( in_array( $level, self::$fatalErrorTypes ) ) {
165 return call_user_func_array(
166 'MWExceptionHandler::handleFatalError', func_get_args()
170 // Map error constant to error name (reverse-engineer PHP error
171 // reporting)
172 switch ( $level ) {
173 case E_RECOVERABLE_ERROR:
174 $levelName = 'Error';
175 break;
176 case E_WARNING:
177 case E_CORE_WARNING:
178 case E_COMPILE_WARNING:
179 case E_USER_WARNING:
180 $levelName = 'Warning';
181 break;
182 case E_NOTICE:
183 case E_USER_NOTICE:
184 $levelName = 'Notice';
185 break;
186 case E_STRICT:
187 $levelName = 'Strict Standards';
188 break;
189 case E_DEPRECATED:
190 case E_USER_DEPRECATED:
191 $levelName = 'Deprecated';
192 break;
193 default:
194 $levelName = 'Unknown error';
195 break;
198 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
199 self::logError( $e, 'error' );
201 // This handler is for logging only. Return false will instruct PHP
202 // to continue regular handling.
203 return false;
207 * Dual purpose callback used as both a set_error_handler() callback and
208 * a registered shutdown function. Receive a callback from the interpreter
209 * for a raised error or system shutdown, check for a fatal error, and log
210 * to the 'fatal' logging channel.
212 * Special handling is included for missing class errors as they may
213 * indicate that the user needs to install 3rd-party libraries via
214 * Composer or other means.
216 * @since 1.25
218 * @param int $level Error level raised
219 * @param string $message Error message
220 * @param string $file File that error was raised in
221 * @param int $line Line number error was raised at
222 * @param array $context Active symbol table point of error
223 * @param array $trace Backtrace at point of error (undocumented HHVM
224 * feature)
225 * @return bool Always returns false
227 public static function handleFatalError(
228 $level = null, $message = null, $file = null, $line = null,
229 $context = null, $trace = null
231 // Free reserved memory so that we have space to process OOM
232 // errors
233 self::$reservedMemory = null;
235 if ( $level === null ) {
236 // Called as a shutdown handler, get data from error_get_last()
237 if ( static::$handledFatalCallback ) {
238 // Already called once (probably as an error handler callback
239 // under HHVM) so don't log again.
240 return false;
243 $lastError = error_get_last();
244 if ( $lastError !== null ) {
245 $level = $lastError['type'];
246 $message = $lastError['message'];
247 $file = $lastError['file'];
248 $line = $lastError['line'];
249 } else {
250 $level = 0;
251 $message = '';
255 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
256 // Only interested in fatal errors, others should have been
257 // handled by MWExceptionHandler::handleError
258 return false;
261 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
263 // Look at message to see if this is a class not found failure
264 // HHVM: Class undefined: foo
265 // PHP5: Class 'foo' not found
266 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
267 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
268 $msg = <<<TXT
269 {$msg}
271 MediaWiki or an installed extension requires this class but it is not embedded directly in MediaWiki's git repository and must be installed separately by the end user.
273 Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
274 TXT;
275 // @codingStandardsIgnoreEnd
278 // We can't just create an exception and log it as it is likely that
279 // the interpreter has unwound the stack already. If that is true the
280 // stacktrace we would get would be functionally empty. If however we
281 // have been called as an error handler callback *and* HHVM is in use
282 // we will have been provided with a useful stacktrace that we can
283 // log.
284 $trace = $trace ?: debug_backtrace();
285 $logger = LoggerFactory::getInstance( 'fatal' );
286 $logger->error( $msg, [
287 'exception' => [
288 'class' => 'ErrorException',
289 'message' => "PHP Fatal Error: {$message}",
290 'code' => $level,
291 'file' => $file,
292 'line' => $line,
293 'trace' => static::redactTrace( $trace ),
295 'exception_id' => wfRandomString( 8 ),
296 ] );
298 // Remember call so we don't double process via HHVM's fatal
299 // notifications and the shutdown hook behavior
300 static::$handledFatalCallback = true;
301 return false;
305 * Generate a string representation of an exception's stack trace
307 * Like Exception::getTraceAsString, but replaces argument values with
308 * argument type or class name.
310 * @param Exception|Throwable $e
311 * @return string
312 * @see prettyPrintTrace()
314 public static function getRedactedTraceAsString( $e ) {
315 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
319 * Generate a string representation of a stacktrace.
321 * @param array $trace
322 * @param string $pad Constant padding to add to each line of trace
323 * @return string
324 * @since 1.26
326 public static function prettyPrintTrace( array $trace, $pad = '' ) {
327 $text = '';
329 $level = 0;
330 foreach ( $trace as $level => $frame ) {
331 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
332 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
333 } else {
334 // 'file' and 'line' are unset for calls via call_user_func
335 // (bug 55634) This matches behaviour of
336 // Exception::getTraceAsString to instead display "[internal
337 // function]".
338 $text .= "{$pad}#{$level} [internal function]: ";
341 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
342 $text .= $frame['class'] . $frame['type'] . $frame['function'];
343 } elseif ( isset( $frame['function'] ) ) {
344 $text .= $frame['function'];
345 } else {
346 $text .= 'NO_FUNCTION_GIVEN';
349 if ( isset( $frame['args'] ) ) {
350 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
351 } else {
352 $text .= "()\n";
356 $level = $level + 1;
357 $text .= "{$pad}#{$level} {main}";
359 return $text;
363 * Return a copy of an exception's backtrace as an array.
365 * Like Exception::getTrace, but replaces each element in each frame's
366 * argument array with the name of its class (if the element is an object)
367 * or its type (if the element is a PHP primitive).
369 * @since 1.22
370 * @param Exception|Throwable $e
371 * @return array
373 public static function getRedactedTrace( $e ) {
374 return static::redactTrace( $e->getTrace() );
378 * Redact a stacktrace generated by Exception::getTrace(),
379 * debug_backtrace() or similar means. Replaces each element in each
380 * frame's argument array with the name of its class (if the element is an
381 * object) or its type (if the element is a PHP primitive).
383 * @since 1.26
384 * @param array $trace Stacktrace
385 * @return array Stacktrace with arugment values converted to data types
387 public static function redactTrace( array $trace ) {
388 return array_map( function ( $frame ) {
389 if ( isset( $frame['args'] ) ) {
390 $frame['args'] = array_map( function ( $arg ) {
391 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
392 }, $frame['args'] );
394 return $frame;
395 }, $trace );
399 * Get the ID for this exception.
401 * The ID is saved so that one can match the one output to the user (when
402 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
404 * @since 1.22
405 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
406 * @param Exception|Throwable $e
407 * @return string
409 public static function getLogId( $e ) {
410 wfDeprecated( __METHOD__, '1.27' );
411 return WebRequest::getRequestId();
415 * If the exception occurred in the course of responding to a request,
416 * returns the requested URL. Otherwise, returns false.
418 * @since 1.23
419 * @return string|false
421 public static function getURL() {
422 global $wgRequest;
423 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
424 return false;
426 return $wgRequest->getRequestURL();
430 * Get a message formatting the exception message and its origin.
432 * @since 1.22
433 * @param Exception|Throwable $e
434 * @return string
436 public static function getLogMessage( $e ) {
437 $id = WebRequest::getRequestId();
438 $type = get_class( $e );
439 $file = $e->getFile();
440 $line = $e->getLine();
441 $message = $e->getMessage();
442 $url = self::getURL() ?: '[no req]';
444 return "[$id] $url $type from line $line of $file: $message";
448 * @param Exception|Throwable $e
449 * @return string
451 public static function getPublicLogMessage( $e ) {
452 $reqId = WebRequest::getRequestId();
453 $type = get_class( $e );
454 return '[' . $reqId . '] '
455 . gmdate( 'Y-m-d H:i:s' ) . ': '
456 . 'Fatal exception of type "' . $type . '"';
460 * Get a PSR-3 log event context from an Exception.
462 * Creates a structured array containing information about the provided
463 * exception that can be used to augment a log message sent to a PSR-3
464 * logger.
466 * @param Exception|Throwable $e
467 * @return array
469 public static function getLogContext( $e ) {
470 return [
471 'exception' => $e,
472 'exception_id' => WebRequest::getRequestId(),
477 * Get a structured representation of an Exception.
479 * Returns an array of structured data (class, message, code, file,
480 * backtrace) derived from the given exception. The backtrace information
481 * will be redacted as per getRedactedTraceAsArray().
483 * @param Exception|Throwable $e
484 * @return array
485 * @since 1.26
487 public static function getStructuredExceptionData( $e ) {
488 global $wgLogExceptionBacktrace;
489 $data = [
490 'id' => WebRequest::getRequestId(),
491 'type' => get_class( $e ),
492 'file' => $e->getFile(),
493 'line' => $e->getLine(),
494 'message' => $e->getMessage(),
495 'code' => $e->getCode(),
496 'url' => self::getURL() ?: null,
499 if ( $e instanceof ErrorException &&
500 ( error_reporting() & $e->getSeverity() ) === 0
502 // Flag surpressed errors
503 $data['suppressed'] = true;
506 if ( $wgLogExceptionBacktrace ) {
507 $data['backtrace'] = self::getRedactedTrace( $e );
510 $previous = $e->getPrevious();
511 if ( $previous !== null ) {
512 $data['previous'] = self::getStructuredExceptionData( $previous );
515 return $data;
519 * Serialize an Exception object to JSON.
521 * The JSON object will have keys 'id', 'file', 'line', 'message', and
522 * 'url'. These keys map to string values, with the exception of 'line',
523 * which is a number, and 'url', which may be either a string URL or or
524 * null if the exception did not occur in the context of serving a web
525 * request.
527 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
528 * key, mapped to the array return value of Exception::getTrace, but with
529 * each element in each frame's "args" array (if set) replaced with the
530 * argument's class name (if the argument is an object) or type name (if
531 * the argument is a PHP primitive).
533 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
534 * @code
536 * "id": "c41fb419",
537 * "type": "MWException",
538 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
539 * "line": 704,
540 * "message": "Non-string key given",
541 * "url": "/wiki/Main_Page"
543 * @endcode
545 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
546 * @code
548 * "id": "dc457938",
549 * "type": "MWException",
550 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
551 * "line": 704,
552 * "message": "Non-string key given",
553 * "url": "/wiki/Main_Page",
554 * "backtrace": [{
555 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
556 * "line": 80,
557 * "function": "get",
558 * "class": "MessageCache",
559 * "type": "->",
560 * "args": ["array"]
561 * }]
563 * @endcode
565 * @since 1.23
566 * @param Exception|Throwable $e
567 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
568 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
569 * @return string|false JSON string if successful; false upon failure
571 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
572 $data = self::getStructuredExceptionData( $e );
573 return FormatJson::encode( $data, $pretty, $escaping );
577 * Log an exception to the exception log (if enabled).
579 * This method must not assume the exception is an MWException,
580 * it is also used to handle PHP exceptions or exceptions from other libraries.
582 * @since 1.22
583 * @param Exception|Throwable $e
585 public static function logException( $e ) {
586 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
587 $logger = LoggerFactory::getInstance( 'exception' );
588 $logger->error(
589 self::getLogMessage( $e ),
590 self::getLogContext( $e )
593 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
594 if ( $json !== false ) {
595 $logger = LoggerFactory::getInstance( 'exception-json' );
596 $logger->error( $json, [ 'private' => true ] );
599 Hooks::run( 'LogException', [ $e, false ] );
604 * Log an exception that wasn't thrown but made to wrap an error.
606 * @since 1.25
607 * @param ErrorException $e
608 * @param string $channel
610 protected static function logError( ErrorException $e, $channel ) {
611 // The set_error_handler callback is independent from error_reporting.
612 // Filter out unwanted errors manually (e.g. when
613 // MediaWiki\suppressWarnings is active).
614 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
615 if ( !$suppressed ) {
616 $logger = LoggerFactory::getInstance( $channel );
617 $logger->error(
618 self::getLogMessage( $e ),
619 self::getLogContext( $e )
623 // Include all errors in the json log (surpressed errors will be flagged)
624 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
625 if ( $json !== false ) {
626 $logger = LoggerFactory::getInstance( "{$channel}-json" );
627 $logger->error( $json, [ 'private' => true ] );
630 Hooks::run( 'LogException', [ $e, $suppressed ] );