Merge "Always log exceptions in rollbackMasterChangesAndLog()"
[lhc/web/wiklou.git] / includes / exception / MWExceptionHandler.php
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\MediaWikiServices;
23 use Psr\Log\LogLevel;
24 use Wikimedia\Rdbms\DBError;
25
26 /**
27 * Handler class for MWExceptions
28 * @ingroup Exception
29 */
30 class MWExceptionHandler {
31 const CAUGHT_BY_HANDLER = 'mwe_handler'; // error reported by this exception handler
32 const CAUGHT_BY_OTHER = 'other'; // error reported by direct logException() call
33
34 /**
35 * @var string $reservedMemory
36 */
37 protected static $reservedMemory;
38 /**
39 * @var array $fatalErrorTypes
40 */
41 protected static $fatalErrorTypes = [
42 E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
43 /* HHVM's FATAL_ERROR level */ 16777217,
44 ];
45 /**
46 * @var bool $handledFatalCallback
47 */
48 protected static $handledFatalCallback = false;
49
50 /**
51 * Install handlers with PHP.
52 */
53 public static function installHandler() {
54 set_exception_handler( 'MWExceptionHandler::handleException' );
55 set_error_handler( 'MWExceptionHandler::handleError' );
56
57 // Reserve 16k of memory so we can report OOM fatals
58 self::$reservedMemory = str_repeat( ' ', 16384 );
59 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
60 }
61
62 /**
63 * Report an exception to the user
64 * @param Exception|Throwable $e
65 */
66 protected static function report( $e ) {
67 try {
68 // Try and show the exception prettily, with the normal skin infrastructure
69 if ( $e instanceof MWException ) {
70 // Delegate to MWException until all subclasses are handled by
71 // MWExceptionRenderer and MWException::report() has been
72 // removed.
73 $e->report();
74 } else {
75 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
76 }
77 } catch ( Exception $e2 ) {
78 // Exception occurred from within exception handler
79 // Show a simpler message for the original exception,
80 // don't try to invoke report()
81 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
82 }
83 }
84
85 /**
86 * Roll back any open database transactions and log the stack trace of the exception
87 *
88 * This method is used to attempt to recover from exceptions
89 *
90 * @since 1.23
91 * @param Exception|Throwable $e
92 */
93 public static function rollbackMasterChangesAndLog( $e ) {
94 $services = MediaWikiServices::getInstance();
95 if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
96 // Rollback DBs to avoid transaction notices. This might fail
97 // to rollback some databases due to connection issues or exceptions.
98 // However, any sane DB driver will rollback implicitly anyway.
99 try {
100 $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__ );
101 } catch ( DBError $e2 ) {
102 // If the DB is unreacheable, rollback() will throw an error
103 // and the error report() method might need messages from the DB,
104 // which would result in an exception loop. PHP may escalate such
105 // errors to "Exception thrown without a stack frame" fatals, but
106 // it's better to be explicit here.
107 self::logException( $e2, self::CAUGHT_BY_HANDLER );
108 }
109 }
110
111 self::logException( $e, self::CAUGHT_BY_HANDLER );
112 }
113
114 /**
115 * Exception handler which simulates the appropriate catch() handling:
116 *
117 * try {
118 * ...
119 * } catch ( Exception $e ) {
120 * $e->report();
121 * } catch ( Exception $e ) {
122 * echo $e->__toString();
123 * }
124 *
125 * @since 1.25
126 * @param Exception|Throwable $e
127 */
128 public static function handleException( $e ) {
129 self::rollbackMasterChangesAndLog( $e );
130 self::report( $e );
131 // Exit value should be nonzero for the benefit of shell jobs
132 exit( 1 );
133 }
134
135 /**
136 * Handler for set_error_handler() callback notifications.
137 *
138 * Receive a callback from the interpreter for a raised error, create an
139 * ErrorException, and log the exception to the 'error' logging
140 * channel(s). If the raised error is a fatal error type (only under HHVM)
141 * delegate to handleFatalError() instead.
142 *
143 * @since 1.25
144 *
145 * @param int $level Error level raised
146 * @param string $message
147 * @param string $file
148 * @param int $line
149 * @return bool
150 *
151 * @see logError()
152 */
153 public static function handleError(
154 $level, $message, $file = null, $line = null
155 ) {
156 if ( in_array( $level, self::$fatalErrorTypes ) ) {
157 return call_user_func_array(
158 'MWExceptionHandler::handleFatalError', func_get_args()
159 );
160 }
161
162 // Map error constant to error name (reverse-engineer PHP error
163 // reporting)
164 switch ( $level ) {
165 case E_RECOVERABLE_ERROR:
166 $levelName = 'Error';
167 $severity = LogLevel::ERROR;
168 break;
169 case E_WARNING:
170 case E_CORE_WARNING:
171 case E_COMPILE_WARNING:
172 case E_USER_WARNING:
173 $levelName = 'Warning';
174 $severity = LogLevel::WARNING;
175 break;
176 case E_NOTICE:
177 case E_USER_NOTICE:
178 $levelName = 'Notice';
179 $severity = LogLevel::INFO;
180 break;
181 case E_STRICT:
182 $levelName = 'Strict Standards';
183 $severity = LogLevel::DEBUG;
184 break;
185 case E_DEPRECATED:
186 case E_USER_DEPRECATED:
187 $levelName = 'Deprecated';
188 $severity = LogLevel::INFO;
189 break;
190 default:
191 $levelName = 'Unknown error';
192 $severity = LogLevel::ERROR;
193 break;
194 }
195
196 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
197 self::logError( $e, 'error', $severity );
198
199 // This handler is for logging only. Return false will instruct PHP
200 // to continue regular handling.
201 return false;
202 }
203
204 /**
205 * Dual purpose callback used as both a set_error_handler() callback and
206 * a registered shutdown function. Receive a callback from the interpreter
207 * for a raised error or system shutdown, check for a fatal error, and log
208 * to the 'fatal' logging channel.
209 *
210 * Special handling is included for missing class errors as they may
211 * indicate that the user needs to install 3rd-party libraries via
212 * Composer or other means.
213 *
214 * @since 1.25
215 *
216 * @param int $level Error level raised
217 * @param string $message Error message
218 * @param string $file File that error was raised in
219 * @param int $line Line number error was raised at
220 * @param array $context Active symbol table point of error
221 * @param array $trace Backtrace at point of error (undocumented HHVM
222 * feature)
223 * @return bool Always returns false
224 */
225 public static function handleFatalError(
226 $level = null, $message = null, $file = null, $line = null,
227 $context = null, $trace = null
228 ) {
229 // Free reserved memory so that we have space to process OOM
230 // errors
231 self::$reservedMemory = null;
232
233 if ( $level === null ) {
234 // Called as a shutdown handler, get data from error_get_last()
235 if ( static::$handledFatalCallback ) {
236 // Already called once (probably as an error handler callback
237 // under HHVM) so don't log again.
238 return false;
239 }
240
241 $lastError = error_get_last();
242 if ( $lastError !== null ) {
243 $level = $lastError['type'];
244 $message = $lastError['message'];
245 $file = $lastError['file'];
246 $line = $lastError['line'];
247 } else {
248 $level = 0;
249 $message = '';
250 }
251 }
252
253 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
254 // Only interested in fatal errors, others should have been
255 // handled by MWExceptionHandler::handleError
256 return false;
257 }
258
259 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
260
261 // Look at message to see if this is a class not found failure
262 // HHVM: Class undefined: foo
263 // PHP5: Class 'foo' not found
264 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
265 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
266 $msg = <<<TXT
267 {$msg}
268
269 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.
270
271 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.
272 TXT;
273 // @codingStandardsIgnoreEnd
274 }
275
276 // We can't just create an exception and log it as it is likely that
277 // the interpreter has unwound the stack already. If that is true the
278 // stacktrace we would get would be functionally empty. If however we
279 // have been called as an error handler callback *and* HHVM is in use
280 // we will have been provided with a useful stacktrace that we can
281 // log.
282 $trace = $trace ?: debug_backtrace();
283 $logger = LoggerFactory::getInstance( 'fatal' );
284 $logger->error( $msg, [
285 'fatal_exception' => [
286 'class' => 'ErrorException',
287 'message' => "PHP Fatal Error: {$message}",
288 'code' => $level,
289 'file' => $file,
290 'line' => $line,
291 'trace' => static::redactTrace( $trace ),
292 ],
293 'exception_id' => wfRandomString( 8 ),
294 'caught_by' => self::CAUGHT_BY_HANDLER
295 ] );
296
297 // Remember call so we don't double process via HHVM's fatal
298 // notifications and the shutdown hook behavior
299 static::$handledFatalCallback = true;
300 return false;
301 }
302
303 /**
304 * Generate a string representation of an exception's stack trace
305 *
306 * Like Exception::getTraceAsString, but replaces argument values with
307 * argument type or class name.
308 *
309 * @param Exception|Throwable $e
310 * @return string
311 * @see prettyPrintTrace()
312 */
313 public static function getRedactedTraceAsString( $e ) {
314 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
315 }
316
317 /**
318 * Generate a string representation of a stacktrace.
319 *
320 * @param array $trace
321 * @param string $pad Constant padding to add to each line of trace
322 * @return string
323 * @since 1.26
324 */
325 public static function prettyPrintTrace( array $trace, $pad = '' ) {
326 $text = '';
327
328 $level = 0;
329 foreach ( $trace as $level => $frame ) {
330 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
331 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
332 } else {
333 // 'file' and 'line' are unset for calls via call_user_func
334 // (T57634) This matches behaviour of
335 // Exception::getTraceAsString to instead display "[internal
336 // function]".
337 $text .= "{$pad}#{$level} [internal function]: ";
338 }
339
340 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
341 $text .= $frame['class'] . $frame['type'] . $frame['function'];
342 } elseif ( isset( $frame['function'] ) ) {
343 $text .= $frame['function'];
344 } else {
345 $text .= 'NO_FUNCTION_GIVEN';
346 }
347
348 if ( isset( $frame['args'] ) ) {
349 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
350 } else {
351 $text .= "()\n";
352 }
353 }
354
355 $level = $level + 1;
356 $text .= "{$pad}#{$level} {main}";
357
358 return $text;
359 }
360
361 /**
362 * Return a copy of an exception's backtrace as an array.
363 *
364 * Like Exception::getTrace, but replaces each element in each frame's
365 * argument array with the name of its class (if the element is an object)
366 * or its type (if the element is a PHP primitive).
367 *
368 * @since 1.22
369 * @param Exception|Throwable $e
370 * @return array
371 */
372 public static function getRedactedTrace( $e ) {
373 return static::redactTrace( $e->getTrace() );
374 }
375
376 /**
377 * Redact a stacktrace generated by Exception::getTrace(),
378 * debug_backtrace() or similar means. Replaces each element in each
379 * frame's argument array with the name of its class (if the element is an
380 * object) or its type (if the element is a PHP primitive).
381 *
382 * @since 1.26
383 * @param array $trace Stacktrace
384 * @return array Stacktrace with arugment values converted to data types
385 */
386 public static function redactTrace( array $trace ) {
387 return array_map( function ( $frame ) {
388 if ( isset( $frame['args'] ) ) {
389 $frame['args'] = array_map( function ( $arg ) {
390 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
391 }, $frame['args'] );
392 }
393 return $frame;
394 }, $trace );
395 }
396
397 /**
398 * Get the ID for this exception.
399 *
400 * The ID is saved so that one can match the one output to the user (when
401 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
402 *
403 * @since 1.22
404 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
405 * @param Exception|Throwable $e
406 * @return string
407 */
408 public static function getLogId( $e ) {
409 wfDeprecated( __METHOD__, '1.27' );
410 return WebRequest::getRequestId();
411 }
412
413 /**
414 * If the exception occurred in the course of responding to a request,
415 * returns the requested URL. Otherwise, returns false.
416 *
417 * @since 1.23
418 * @return string|false
419 */
420 public static function getURL() {
421 global $wgRequest;
422 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
423 return false;
424 }
425 return $wgRequest->getRequestURL();
426 }
427
428 /**
429 * Get a message formatting the exception message and its origin.
430 *
431 * @since 1.22
432 * @param Exception|Throwable $e
433 * @return string
434 */
435 public static function getLogMessage( $e ) {
436 $id = WebRequest::getRequestId();
437 $type = get_class( $e );
438 $file = $e->getFile();
439 $line = $e->getLine();
440 $message = $e->getMessage();
441 $url = self::getURL() ?: '[no req]';
442
443 return "[$id] $url $type from line $line of $file: $message";
444 }
445
446 /**
447 * @param Exception|Throwable $e
448 * @return string
449 */
450 public static function getPublicLogMessage( $e ) {
451 $reqId = WebRequest::getRequestId();
452 $type = get_class( $e );
453 return '[' . $reqId . '] '
454 . gmdate( 'Y-m-d H:i:s' ) . ': '
455 . 'Fatal exception of type "' . $type . '"';
456 }
457
458 /**
459 * Get a PSR-3 log event context from an Exception.
460 *
461 * Creates a structured array containing information about the provided
462 * exception that can be used to augment a log message sent to a PSR-3
463 * logger.
464 *
465 * @param Exception|Throwable $e
466 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
467 * @return array
468 */
469 public static function getLogContext( $e, $catcher = self::CAUGHT_BY_OTHER ) {
470 return [
471 'exception' => $e,
472 'exception_id' => WebRequest::getRequestId(),
473 'caught_by' => $catcher
474 ];
475 }
476
477 /**
478 * Get a structured representation of an Exception.
479 *
480 * Returns an array of structured data (class, message, code, file,
481 * backtrace) derived from the given exception. The backtrace information
482 * will be redacted as per getRedactedTraceAsArray().
483 *
484 * @param Exception|Throwable $e
485 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
486 * @return array
487 * @since 1.26
488 */
489 public static function getStructuredExceptionData( $e, $catcher = self::CAUGHT_BY_OTHER ) {
490 global $wgLogExceptionBacktrace;
491
492 $data = [
493 'id' => WebRequest::getRequestId(),
494 'type' => get_class( $e ),
495 'file' => $e->getFile(),
496 'line' => $e->getLine(),
497 'message' => $e->getMessage(),
498 'code' => $e->getCode(),
499 'url' => self::getURL() ?: null,
500 'caught_by' => $catcher
501 ];
502
503 if ( $e instanceof ErrorException &&
504 ( error_reporting() & $e->getSeverity() ) === 0
505 ) {
506 // Flag surpressed errors
507 $data['suppressed'] = true;
508 }
509
510 if ( $wgLogExceptionBacktrace ) {
511 $data['backtrace'] = self::getRedactedTrace( $e );
512 }
513
514 $previous = $e->getPrevious();
515 if ( $previous !== null ) {
516 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
517 }
518
519 return $data;
520 }
521
522 /**
523 * Serialize an Exception object to JSON.
524 *
525 * The JSON object will have keys 'id', 'file', 'line', 'message', and
526 * 'url'. These keys map to string values, with the exception of 'line',
527 * which is a number, and 'url', which may be either a string URL or or
528 * null if the exception did not occur in the context of serving a web
529 * request.
530 *
531 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
532 * key, mapped to the array return value of Exception::getTrace, but with
533 * each element in each frame's "args" array (if set) replaced with the
534 * argument's class name (if the argument is an object) or type name (if
535 * the argument is a PHP primitive).
536 *
537 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
538 * @code
539 * {
540 * "id": "c41fb419",
541 * "type": "MWException",
542 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
543 * "line": 704,
544 * "message": "Non-string key given",
545 * "url": "/wiki/Main_Page"
546 * }
547 * @endcode
548 *
549 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
550 * @code
551 * {
552 * "id": "dc457938",
553 * "type": "MWException",
554 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
555 * "line": 704,
556 * "message": "Non-string key given",
557 * "url": "/wiki/Main_Page",
558 * "backtrace": [{
559 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
560 * "line": 80,
561 * "function": "get",
562 * "class": "MessageCache",
563 * "type": "->",
564 * "args": ["array"]
565 * }]
566 * }
567 * @endcode
568 *
569 * @since 1.23
570 * @param Exception|Throwable $e
571 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
572 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
573 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
574 * @return string|false JSON string if successful; false upon failure
575 */
576 public static function jsonSerializeException(
577 $e, $pretty = false, $escaping = 0, $catcher = self::CAUGHT_BY_OTHER
578 ) {
579 return FormatJson::encode(
580 self::getStructuredExceptionData( $e, $catcher ),
581 $pretty,
582 $escaping
583 );
584 }
585
586 /**
587 * Log an exception to the exception log (if enabled).
588 *
589 * This method must not assume the exception is an MWException,
590 * it is also used to handle PHP exceptions or exceptions from other libraries.
591 *
592 * @since 1.22
593 * @param Exception|Throwable $e
594 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
595 */
596 public static function logException( $e, $catcher = self::CAUGHT_BY_OTHER ) {
597 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
598 $logger = LoggerFactory::getInstance( 'exception' );
599 $logger->error(
600 self::getLogMessage( $e ),
601 self::getLogContext( $e, $catcher )
602 );
603
604 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
605 if ( $json !== false ) {
606 $logger = LoggerFactory::getInstance( 'exception-json' );
607 $logger->error( $json, [ 'private' => true ] );
608 }
609
610 Hooks::run( 'LogException', [ $e, false ] );
611 }
612 }
613
614 /**
615 * Log an exception that wasn't thrown but made to wrap an error.
616 *
617 * @since 1.25
618 * @param ErrorException $e
619 * @param string $channel
620 * @param string $level
621 */
622 protected static function logError(
623 ErrorException $e, $channel, $level = LogLevel::ERROR
624 ) {
625 $catcher = self::CAUGHT_BY_HANDLER;
626 // The set_error_handler callback is independent from error_reporting.
627 // Filter out unwanted errors manually (e.g. when
628 // MediaWiki\suppressWarnings is active).
629 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
630 if ( !$suppressed ) {
631 $logger = LoggerFactory::getInstance( $channel );
632 $logger->log(
633 $level,
634 self::getLogMessage( $e ),
635 self::getLogContext( $e, $catcher )
636 );
637 }
638
639 // Include all errors in the json log (surpressed errors will be flagged)
640 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
641 if ( $json !== false ) {
642 $logger = LoggerFactory::getInstance( "{$channel}-json" );
643 $logger->log( $level, $json, [ 'private' => true ] );
644 }
645
646 Hooks::run( 'LogException', [ $e, $suppressed ] );
647 }
648 }