| 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\Debug\MWDebug; |
| 22 | use MediaWiki\HookContainer\HookRunner; |
| 23 | use MediaWiki\Json\FormatJson; |
| 24 | use MediaWiki\Logger\LoggerFactory; |
| 25 | use MediaWiki\MediaWikiServices; |
| 26 | use MediaWiki\Request\WebRequest; |
| 27 | use Psr\Log\LogLevel; |
| 28 | use Wikimedia\NormalizedException\INormalizedException; |
| 29 | use Wikimedia\Rdbms\DBError; |
| 30 | use Wikimedia\Rdbms\DBQueryError; |
| 31 | use Wikimedia\Rdbms\LBFactory; |
| 32 | use Wikimedia\Services\RecursiveServiceDependencyException; |
| 33 | |
| 34 | /** |
| 35 | * Handler class for MWExceptions |
| 36 | * @ingroup Exception |
| 37 | */ |
| 38 | class MWExceptionHandler { |
| 39 | /** Error caught and reported by this exception handler */ |
| 40 | public const CAUGHT_BY_HANDLER = 'mwe_handler'; |
| 41 | /** Error caught and reported by a script entry point */ |
| 42 | public const CAUGHT_BY_ENTRYPOINT = 'entrypoint'; |
| 43 | /** Error reported by direct logException() call */ |
| 44 | public const CAUGHT_BY_OTHER = 'other'; |
| 45 | |
| 46 | /** @var string|null */ |
| 47 | protected static $reservedMemory; |
| 48 | |
| 49 | /** |
| 50 | * Error types that, if unhandled, are fatal to the request. |
| 51 | * These error types may be thrown as Error objects, which implement Throwable (but not Exception). |
| 52 | * |
| 53 | * The user will be shown an HTTP 500 Internal Server Error. |
| 54 | * As such, these should be sent to MediaWiki's "exception" channel. |
| 55 | * Normally, the error handler logs them to the "error" channel. |
| 56 | */ |
| 57 | private const FATAL_ERROR_TYPES = [ |
| 58 | E_ERROR, |
| 59 | E_PARSE, |
| 60 | E_CORE_ERROR, |
| 61 | E_COMPILE_ERROR, |
| 62 | E_USER_ERROR, |
| 63 | |
| 64 | // E.g. "Catchable fatal error: Argument X must be Y, null given" |
| 65 | E_RECOVERABLE_ERROR, |
| 66 | ]; |
| 67 | |
| 68 | /** |
| 69 | * Whether exception data should include a backtrace. |
| 70 | * |
| 71 | * @var bool |
| 72 | */ |
| 73 | private static $logExceptionBacktrace = true; |
| 74 | |
| 75 | /** |
| 76 | * Whether to propagate errors to PHP's built-in handler. |
| 77 | * |
| 78 | * @var bool |
| 79 | */ |
| 80 | private static $propagateErrors; |
| 81 | |
| 82 | /** |
| 83 | * Install handlers with PHP. |
| 84 | * @internal |
| 85 | * @param bool $logExceptionBacktrace Whether error handlers should include a backtrace |
| 86 | * in the log. |
| 87 | * @param bool $propagateErrors Whether errors should be propagated to PHP's built-in handler. |
| 88 | */ |
| 89 | public static function installHandler( |
| 90 | bool $logExceptionBacktrace = true, |
| 91 | bool $propagateErrors = true |
| 92 | ) { |
| 93 | self::$logExceptionBacktrace = $logExceptionBacktrace; |
| 94 | self::$propagateErrors = $propagateErrors; |
| 95 | |
| 96 | // This catches: |
| 97 | // * Exception objects that were explicitly thrown but not |
| 98 | // caught anywhere in the application. This is rare given those |
| 99 | // would normally be caught at a high-level like MediaWiki::run (index.php), |
| 100 | // api.php, or ResourceLoader::respond (load.php). These high-level |
| 101 | // catch clauses would then call MWExceptionHandler::logException |
| 102 | // or MWExceptionHandler::handleException. |
| 103 | // If they are not caught, then they are handled here. |
| 104 | // * Error objects for issues that would historically |
| 105 | // cause fatal errors but may now be caught as Throwable (not Exception). |
| 106 | // Same as previous case, but more common to bubble to here instead of |
| 107 | // caught locally because they tend to not be safe to recover from. |
| 108 | // (e.g. argument TypeError, division by zero, etc.) |
| 109 | set_exception_handler( [ self::class, 'handleUncaughtException' ] ); |
| 110 | |
| 111 | // This catches recoverable errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not |
| 112 | // interrupt execution in any way. We log these in the background and then continue execution. |
| 113 | set_error_handler( [ self::class, 'handleError' ] ); |
| 114 | |
| 115 | // This catches fatal errors for which no Throwable is thrown, |
| 116 | // including Out-Of-Memory and Timeout fatals. |
| 117 | // Reserve 16k of memory so we can report OOM fatals. |
| 118 | self::$reservedMemory = str_repeat( ' ', 16384 ); |
| 119 | register_shutdown_function( [ self::class, 'handleFatalError' ] ); |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Report a throwable to the user |
| 124 | * @param Throwable $e |
| 125 | */ |
| 126 | protected static function report( Throwable $e ) { |
| 127 | try { |
| 128 | // Try and show the exception prettily, with the normal skin infrastructure |
| 129 | if ( $e instanceof MWException && $e->hasOverriddenHandler() ) { |
| 130 | // Delegate to MWException until all subclasses are handled by |
| 131 | // MWExceptionRenderer and MWException::report() has been |
| 132 | // removed. |
| 133 | $e->report(); |
| 134 | } else { |
| 135 | MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY ); |
| 136 | } |
| 137 | } catch ( Throwable $e2 ) { |
| 138 | // Exception occurred from within exception handler |
| 139 | // Show a simpler message for the original exception, |
| 140 | // don't try to invoke report() |
| 141 | MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 ); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /** |
| 146 | * Roll back any open database transactions |
| 147 | * |
| 148 | * This method is used to attempt to recover from exceptions |
| 149 | */ |
| 150 | private static function rollbackPrimaryChanges() { |
| 151 | if ( !MediaWikiServices::hasInstance() ) { |
| 152 | // MediaWiki isn't fully initialized yet, it's not safe to access services. |
| 153 | // This also means that there's nothing to roll back yet. |
| 154 | return; |
| 155 | } |
| 156 | |
| 157 | $services = MediaWikiServices::getInstance(); |
| 158 | $lbFactory = $services->peekService( 'DBLoadBalancerFactory' ); |
| 159 | '@phan-var LBFactory $lbFactory'; /* @var LBFactory $lbFactory */ |
| 160 | if ( !$lbFactory ) { |
| 161 | // There's no need to roll back transactions if the LBFactory is |
| 162 | // disabled or hasn't been created yet |
| 163 | return; |
| 164 | } |
| 165 | |
| 166 | // Roll back DBs to avoid transaction notices. This might fail |
| 167 | // to roll back some databases due to connection issues or exceptions. |
| 168 | // However, any sensible DB driver will roll back implicitly anyway. |
| 169 | try { |
| 170 | $lbFactory->rollbackPrimaryChanges( __METHOD__ ); |
| 171 | $lbFactory->flushPrimarySessions( __METHOD__ ); |
| 172 | } catch ( DBError $e ) { |
| 173 | // If the DB is unreachable, rollback() will throw an error |
| 174 | // and the error report() method might need messages from the DB, |
| 175 | // which would result in an exception loop. PHP may escalate such |
| 176 | // errors to "Exception thrown without a stack frame" fatals, but |
| 177 | // it's better to be explicit here. |
| 178 | self::logException( $e, self::CAUGHT_BY_HANDLER ); |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * Roll back any open database transactions and log the stack trace of the throwable |
| 184 | * |
| 185 | * This method is used to attempt to recover from exceptions |
| 186 | * |
| 187 | * @since 1.37 |
| 188 | * @param Throwable $e |
| 189 | * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error |
| 190 | */ |
| 191 | public static function rollbackPrimaryChangesAndLog( |
| 192 | Throwable $e, |
| 193 | $catcher = self::CAUGHT_BY_OTHER |
| 194 | ) { |
| 195 | self::rollbackPrimaryChanges(); |
| 196 | |
| 197 | self::logException( $e, $catcher ); |
| 198 | } |
| 199 | |
| 200 | /** |
| 201 | * Callback to use with PHP's set_exception_handler. |
| 202 | * |
| 203 | * @since 1.31 |
| 204 | * @param Throwable $e |
| 205 | */ |
| 206 | public static function handleUncaughtException( Throwable $e ) { |
| 207 | self::handleException( $e, self::CAUGHT_BY_HANDLER ); |
| 208 | |
| 209 | // Make sure we don't claim success on exit for CLI scripts (T177414) |
| 210 | if ( wfIsCLI() ) { |
| 211 | register_shutdown_function( |
| 212 | /** |
| 213 | * @return never |
| 214 | */ |
| 215 | static function () { |
| 216 | exit( 255 ); |
| 217 | } |
| 218 | ); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * Exception handler which simulates the appropriate catch() handling: |
| 224 | * |
| 225 | * try { |
| 226 | * ... |
| 227 | * } catch ( Exception $e ) { |
| 228 | * $e->report(); |
| 229 | * } catch ( Exception $e ) { |
| 230 | * echo $e->__toString(); |
| 231 | * } |
| 232 | * |
| 233 | * @since 1.25 |
| 234 | * @param Throwable $e |
| 235 | * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error |
| 236 | */ |
| 237 | public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) { |
| 238 | self::rollbackPrimaryChangesAndLog( $e, $catcher ); |
| 239 | self::report( $e ); |
| 240 | } |
| 241 | |
| 242 | /** |
| 243 | * Handler for set_error_handler() callback notifications. |
| 244 | * |
| 245 | * Receive a callback from the interpreter for a raised error, create an |
| 246 | * ErrorException, and log the exception to the 'error' logging |
| 247 | * channel(s). |
| 248 | * |
| 249 | * @since 1.25 |
| 250 | * @param int $level Error level raised |
| 251 | * @param string $message |
| 252 | * @param string|null $file |
| 253 | * @param int|null $line |
| 254 | * @return bool |
| 255 | */ |
| 256 | public static function handleError( |
| 257 | $level, |
| 258 | $message, |
| 259 | $file = null, |
| 260 | $line = null |
| 261 | ) { |
| 262 | // E_STRICT is deprecated since PHP 8.4 (T375707). |
| 263 | // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged |
| 264 | if ( defined( 'E_STRICT' ) && $level == @constant( 'E_STRICT' ) ) { |
| 265 | $level = E_USER_NOTICE; |
| 266 | } |
| 267 | |
| 268 | // Map PHP error constant to a PSR-3 severity level. |
| 269 | // Avoid use of "DEBUG" or "INFO" levels, unless the |
| 270 | // error should evade error monitoring and alerts. |
| 271 | // |
| 272 | // To decide the log level, ask yourself: "Has the |
| 273 | // program's behaviour diverged from what the written |
| 274 | // code expected?" |
| 275 | // |
| 276 | // For example, use of a deprecated method or violating a strict standard |
| 277 | // has no impact on functional behaviour (Warning). On the other hand, |
| 278 | // accessing an undefined variable makes behaviour diverge from what the |
| 279 | // author intended/expected. PHP recovers from an undefined variables by |
| 280 | // yielding null and continuing execution, but it remains a change in |
| 281 | // behaviour given the null was not part of the code and is likely not |
| 282 | // accounted for. |
| 283 | switch ( $level ) { |
| 284 | case E_WARNING: |
| 285 | case E_CORE_WARNING: |
| 286 | case E_COMPILE_WARNING: |
| 287 | $prefix = 'PHP Warning: '; |
| 288 | $severity = LogLevel::ERROR; |
| 289 | break; |
| 290 | case E_NOTICE: |
| 291 | $prefix = 'PHP Notice: '; |
| 292 | $severity = LogLevel::ERROR; |
| 293 | break; |
| 294 | case E_USER_NOTICE: |
| 295 | // Used by wfWarn(), MWDebug::warning() |
| 296 | $prefix = 'PHP Notice: '; |
| 297 | $severity = LogLevel::WARNING; |
| 298 | break; |
| 299 | case E_USER_WARNING: |
| 300 | // Used by wfWarn(), MWDebug::warning() |
| 301 | $prefix = 'PHP Warning: '; |
| 302 | $severity = LogLevel::WARNING; |
| 303 | break; |
| 304 | case E_DEPRECATED: |
| 305 | $prefix = 'PHP Deprecated: '; |
| 306 | $severity = LogLevel::WARNING; |
| 307 | break; |
| 308 | case E_USER_DEPRECATED: |
| 309 | $prefix = 'PHP Deprecated: '; |
| 310 | $severity = LogLevel::WARNING; |
| 311 | $real = MWDebug::parseCallerDescription( $message ); |
| 312 | if ( $real ) { |
| 313 | // Used by wfDeprecated(), MWDebug::deprecated() |
| 314 | // Apply caller offset from wfDeprecated() to the native error. |
| 315 | // This makes errors easier to aggregate and find in e.g. Kibana. |
| 316 | $file = $real['file']; |
| 317 | $line = $real['line']; |
| 318 | $message = $real['message']; |
| 319 | } |
| 320 | break; |
| 321 | default: |
| 322 | $prefix = 'PHP Unknown error: '; |
| 323 | $severity = LogLevel::ERROR; |
| 324 | break; |
| 325 | } |
| 326 | |
| 327 | // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive |
| 328 | $e = new ErrorException( $prefix . $message, 0, $level, $file, $line ); |
| 329 | self::logError( $e, $severity, self::CAUGHT_BY_HANDLER ); |
| 330 | |
| 331 | // If $propagateErrors is true return false so PHP shows/logs the error normally. |
| 332 | // Ignore $propagateErrors if track_errors is set |
| 333 | // (which means someone is counting on regular PHP error handling behavior). |
| 334 | return !( self::$propagateErrors || ini_get( 'track_errors' ) ); |
| 335 | } |
| 336 | |
| 337 | /** |
| 338 | * Callback used as a registered shutdown function. |
| 339 | * |
| 340 | * This is used as callback from the interpreter at system shutdown. |
| 341 | * If the last error was not a recoverable error that we already reported, |
| 342 | * and log as fatal exception. |
| 343 | * |
| 344 | * Special handling is included for missing class errors as they may |
| 345 | * indicate that the user needs to install 3rd-party libraries via |
| 346 | * Composer or other means. |
| 347 | * |
| 348 | * @since 1.25 |
| 349 | * @return bool Always returns false |
| 350 | */ |
| 351 | public static function handleFatalError() { |
| 352 | // Free reserved memory so that we have space to process OOM |
| 353 | // errors |
| 354 | self::$reservedMemory = null; |
| 355 | |
| 356 | $lastError = error_get_last(); |
| 357 | if ( $lastError === null ) { |
| 358 | return false; |
| 359 | } |
| 360 | |
| 361 | $level = $lastError['type']; |
| 362 | $message = $lastError['message']; |
| 363 | $file = $lastError['file']; |
| 364 | $line = $lastError['line']; |
| 365 | |
| 366 | if ( !in_array( $level, self::FATAL_ERROR_TYPES ) ) { |
| 367 | // Only interested in fatal errors, others should have been |
| 368 | // handled by MWExceptionHandler::handleError |
| 369 | return false; |
| 370 | } |
| 371 | |
| 372 | $msgParts = [ |
| 373 | '[{reqId}] {exception_url} PHP Fatal Error', |
| 374 | ( $line || $file ) ? ' from' : '', |
| 375 | $line ? " line $line" : '', |
| 376 | ( $line && $file ) ? ' of' : '', |
| 377 | $file ? " $file" : '', |
| 378 | ": $message", |
| 379 | ]; |
| 380 | $msg = implode( '', $msgParts ); |
| 381 | |
| 382 | // Look at message to see if this is a class not found failure (Class 'foo' not found) |
| 383 | if ( preg_match( "/Class '\w+' not found/", $message ) ) { |
| 384 | // phpcs:disable Generic.Files.LineLength |
| 385 | $msg = <<<TXT |
| 386 | {$msg} |
| 387 | |
| 388 | 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. |
| 389 | |
| 390 | 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. |
| 391 | TXT; |
| 392 | // phpcs:enable |
| 393 | } |
| 394 | |
| 395 | $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line ); |
| 396 | $logger = LoggerFactory::getInstance( 'exception' ); |
| 397 | $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) ); |
| 398 | |
| 399 | return false; |
| 400 | } |
| 401 | |
| 402 | /** |
| 403 | * Generate a string representation of a throwable's stack trace |
| 404 | * |
| 405 | * Like Throwable::getTraceAsString, but replaces argument values with |
| 406 | * their type or class name, and prepends the start line of the throwable. |
| 407 | * |
| 408 | * @param Throwable $e |
| 409 | * @return string |
| 410 | * @see prettyPrintTrace() |
| 411 | */ |
| 412 | public static function getRedactedTraceAsString( Throwable $e ) { |
| 413 | $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n"; |
| 414 | return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) ); |
| 415 | } |
| 416 | |
| 417 | /** |
| 418 | * Generate a string representation of a stacktrace. |
| 419 | * |
| 420 | * @since 1.26 |
| 421 | * @param array $trace |
| 422 | * @param string $pad Constant padding to add to each line of trace |
| 423 | * @return string |
| 424 | */ |
| 425 | public static function prettyPrintTrace( array $trace, $pad = '' ) { |
| 426 | $text = ''; |
| 427 | |
| 428 | $level = 0; |
| 429 | foreach ( $trace as $level => $frame ) { |
| 430 | if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) { |
| 431 | $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): "; |
| 432 | } else { |
| 433 | // 'file' and 'line' are unset for calls from C code |
| 434 | // (T57634) This matches behaviour of |
| 435 | // Throwable::getTraceAsString to instead display "[internal |
| 436 | // function]". |
| 437 | $text .= "{$pad}#{$level} [internal function]: "; |
| 438 | } |
| 439 | |
| 440 | if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) { |
| 441 | $text .= $frame['class'] . $frame['type'] . $frame['function']; |
| 442 | } else { |
| 443 | $text .= $frame['function'] ?? 'NO_FUNCTION_GIVEN'; |
| 444 | } |
| 445 | |
| 446 | if ( isset( $frame['args'] ) ) { |
| 447 | $text .= '(' . implode( ', ', $frame['args'] ) . ")\n"; |
| 448 | } else { |
| 449 | $text .= "()\n"; |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | $level++; |
| 454 | $text .= "{$pad}#{$level} {main}"; |
| 455 | |
| 456 | return $text; |
| 457 | } |
| 458 | |
| 459 | /** |
| 460 | * Return a copy of a throwable's backtrace as an array. |
| 461 | * |
| 462 | * Like Throwable::getTrace, but replaces each element in each frame's |
| 463 | * argument array with the name of its class (if the element is an object) |
| 464 | * or its type (if the element is a PHP primitive). |
| 465 | * |
| 466 | * @since 1.22 |
| 467 | * @param Throwable $e |
| 468 | * @return array |
| 469 | */ |
| 470 | public static function getRedactedTrace( Throwable $e ) { |
| 471 | return static::redactTrace( $e->getTrace() ); |
| 472 | } |
| 473 | |
| 474 | /** |
| 475 | * Redact a stacktrace generated by Throwable::getTrace(), |
| 476 | * debug_backtrace() or similar means. Replaces each element in each |
| 477 | * frame's argument array with the name of its class (if the element is an |
| 478 | * object) or its type (if the element is a PHP primitive). |
| 479 | * |
| 480 | * @since 1.26 |
| 481 | * @param array $trace Stacktrace |
| 482 | * @return array Stacktrace with argument values converted to data types |
| 483 | */ |
| 484 | public static function redactTrace( array $trace ) { |
| 485 | return array_map( static function ( $frame ) { |
| 486 | if ( isset( $frame['args'] ) ) { |
| 487 | $frame['args'] = array_map( 'get_debug_type', $frame['args'] ); |
| 488 | } |
| 489 | return $frame; |
| 490 | }, $trace ); |
| 491 | } |
| 492 | |
| 493 | /** |
| 494 | * If the exception occurred in the course of responding to a request, |
| 495 | * returns the requested URL. Otherwise, returns false. |
| 496 | * |
| 497 | * @since 1.23 |
| 498 | * @return string|false |
| 499 | */ |
| 500 | public static function getURL() { |
| 501 | if ( MW_ENTRY_POINT === 'cli' ) { |
| 502 | return false; |
| 503 | } |
| 504 | return WebRequest::getGlobalRequestURL(); |
| 505 | } |
| 506 | |
| 507 | /** |
| 508 | * Get a message formatting the throwable message and its origin. |
| 509 | * |
| 510 | * Despite the method name, this is not used for logging. |
| 511 | * It is only used for HTML or CLI output by MWExceptionRenderer. |
| 512 | * |
| 513 | * @since 1.22 |
| 514 | * @param Throwable $e |
| 515 | * @return string |
| 516 | */ |
| 517 | public static function getLogMessage( Throwable $e ) { |
| 518 | $id = WebRequest::getRequestId(); |
| 519 | $type = get_class( $e ); |
| 520 | $message = $e->getMessage(); |
| 521 | $url = self::getURL() ?: '[no req]'; |
| 522 | |
| 523 | if ( $e instanceof DBQueryError ) { |
| 524 | $message = "A database query error has occurred. Did you forget to run" |
| 525 | . " your application's database schema updater after upgrading" |
| 526 | . " or after adding a new extension?\n\nPlease see" |
| 527 | . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and" |
| 528 | . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug" |
| 529 | . " for more information.\n\n" |
| 530 | . $message; |
| 531 | } |
| 532 | |
| 533 | return "[$id] $url $type: $message"; |
| 534 | } |
| 535 | |
| 536 | /** |
| 537 | * Get a normalised message for formatting with PSR-3 log event context. |
| 538 | * |
| 539 | * Must be used together with `getLogContext()` to be useful. |
| 540 | * |
| 541 | * @since 1.30 |
| 542 | * @param Throwable $e |
| 543 | * @return string |
| 544 | */ |
| 545 | public static function getLogNormalMessage( Throwable $e ) { |
| 546 | if ( $e instanceof INormalizedException ) { |
| 547 | $message = $e->getNormalizedMessage(); |
| 548 | } else { |
| 549 | $message = $e->getMessage(); |
| 550 | } |
| 551 | if ( !$e instanceof ErrorException ) { |
| 552 | // ErrorException is something we use internally to represent |
| 553 | // PHP errors (runtime warnings that aren't thrown or caught), |
| 554 | // don't bother putting it in the logs. Let the log message |
| 555 | // lead with "PHP Warning: " instead (see ::handleError). |
| 556 | $message = get_class( $e ) . ": $message"; |
| 557 | } |
| 558 | |
| 559 | return "[{reqId}] {exception_url} $message"; |
| 560 | } |
| 561 | |
| 562 | /** |
| 563 | * @param Throwable $e |
| 564 | * @return string |
| 565 | */ |
| 566 | public static function getPublicLogMessage( Throwable $e ) { |
| 567 | $reqId = WebRequest::getRequestId(); |
| 568 | $type = get_class( $e ); |
| 569 | return '[' . $reqId . '] ' |
| 570 | . gmdate( 'Y-m-d H:i:s' ) . ': ' |
| 571 | . 'Fatal exception of type "' . $type . '"'; |
| 572 | } |
| 573 | |
| 574 | /** |
| 575 | * Get a PSR-3 log event context from a Throwable. |
| 576 | * |
| 577 | * Creates a structured array containing information about the provided |
| 578 | * throwable that can be used to augment a log message sent to a PSR-3 |
| 579 | * logger. |
| 580 | * |
| 581 | * @since 1.26 |
| 582 | * @param Throwable $e |
| 583 | * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error |
| 584 | * @return array |
| 585 | */ |
| 586 | public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) { |
| 587 | $context = [ |
| 588 | 'exception' => $e, |
| 589 | 'exception_url' => self::getURL() ?: '[no req]', |
| 590 | // The reqId context key use the same familiar name and value as the top-level field |
| 591 | // provided by LogstashFormatter. However, formatters are configurable at run-time, |
| 592 | // and their top-level fields are logically separate from context keys and cannot be, |
| 593 | // substituted in a message, hence set explicitly here. For WMF users, these may feel, |
| 594 | // like the same thing due to Monolog V0 handling, which transmits "fields" and "context", |
| 595 | // in the same JSON object (after message formatting). |
| 596 | 'reqId' => WebRequest::getRequestId(), |
| 597 | 'caught_by' => $catcher |
| 598 | ]; |
| 599 | if ( $e instanceof INormalizedException ) { |
| 600 | $context += $e->getMessageContext(); |
| 601 | } |
| 602 | return $context; |
| 603 | } |
| 604 | |
| 605 | /** |
| 606 | * Get a structured representation of a Throwable. |
| 607 | * |
| 608 | * Returns an array of structured data (class, message, code, file, |
| 609 | * backtrace) derived from the given throwable. The backtrace information |
| 610 | * will be redacted as per getRedactedTraceAsArray(). |
| 611 | * |
| 612 | * @param Throwable $e |
| 613 | * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error |
| 614 | * @return array |
| 615 | * @since 1.26 |
| 616 | */ |
| 617 | public static function getStructuredExceptionData( |
| 618 | Throwable $e, |
| 619 | $catcher = self::CAUGHT_BY_OTHER |
| 620 | ) { |
| 621 | $data = [ |
| 622 | 'id' => WebRequest::getRequestId(), |
| 623 | 'type' => get_class( $e ), |
| 624 | 'file' => $e->getFile(), |
| 625 | 'line' => $e->getLine(), |
| 626 | 'message' => $e->getMessage(), |
| 627 | 'code' => $e->getCode(), |
| 628 | 'url' => self::getURL() ?: null, |
| 629 | 'caught_by' => $catcher |
| 630 | ]; |
| 631 | |
| 632 | if ( $e instanceof ErrorException && |
| 633 | ( error_reporting() & $e->getSeverity() ) === 0 |
| 634 | ) { |
| 635 | // Flag suppressed errors |
| 636 | $data['suppressed'] = true; |
| 637 | } |
| 638 | |
| 639 | if ( self::$logExceptionBacktrace ) { |
| 640 | $data['backtrace'] = self::getRedactedTrace( $e ); |
| 641 | } |
| 642 | |
| 643 | $previous = $e->getPrevious(); |
| 644 | if ( $previous !== null ) { |
| 645 | $data['previous'] = self::getStructuredExceptionData( $previous, $catcher ); |
| 646 | } |
| 647 | |
| 648 | return $data; |
| 649 | } |
| 650 | |
| 651 | /** |
| 652 | * Serialize a Throwable object to JSON. |
| 653 | * |
| 654 | * The JSON object will have keys 'id', 'file', 'line', 'message', and |
| 655 | * 'url'. These keys map to string values, with the exception of 'line', |
| 656 | * which is a number, and 'url', which may be either a string URL or |
| 657 | * null if the throwable did not occur in the context of serving a web |
| 658 | * request. |
| 659 | * |
| 660 | * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace' |
| 661 | * key, mapped to the array return value of Throwable::getTrace, but with |
| 662 | * each element in each frame's "args" array (if set) replaced with the |
| 663 | * argument's class name (if the argument is an object) or type name (if |
| 664 | * the argument is a PHP primitive). |
| 665 | * |
| 666 | * @par Sample JSON record ($wgLogExceptionBacktrace = false): |
| 667 | * @code |
| 668 | * { |
| 669 | * "id": "c41fb419", |
| 670 | * "type": "Exception", |
| 671 | * "file": "/var/www/mediawiki/includes/cache/MessageCache.php", |
| 672 | * "line": 704, |
| 673 | * "message": "Example message", |
| 674 | * "url": "/wiki/Main_Page" |
| 675 | * } |
| 676 | * @endcode |
| 677 | * |
| 678 | * @par Sample JSON record ($wgLogExceptionBacktrace = true): |
| 679 | * @code |
| 680 | * { |
| 681 | * "id": "dc457938", |
| 682 | * "type": "Exception", |
| 683 | * "file": "/var/www/mediawiki/includes/cache/MessageCache.php", |
| 684 | * "line": 704, |
| 685 | * "message": "Example message", |
| 686 | * "url": "/wiki/Main_Page", |
| 687 | * "backtrace": [{ |
| 688 | * "file": "/var/www/mediawiki/includes/OutputPage.php", |
| 689 | * "line": 80, |
| 690 | * "function": "get", |
| 691 | * "class": "MessageCache", |
| 692 | * "type": "->", |
| 693 | * "args": ["array"] |
| 694 | * }] |
| 695 | * } |
| 696 | * @endcode |
| 697 | * |
| 698 | * @since 1.23 |
| 699 | * @param Throwable $e |
| 700 | * @param bool $pretty Add non-significant whitespace to improve readability (default: false). |
| 701 | * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants. |
| 702 | * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error |
| 703 | * @return string|false JSON string if successful; false upon failure |
| 704 | */ |
| 705 | public static function jsonSerializeException( |
| 706 | Throwable $e, |
| 707 | $pretty = false, |
| 708 | $escaping = 0, |
| 709 | $catcher = self::CAUGHT_BY_OTHER |
| 710 | ) { |
| 711 | return FormatJson::encode( |
| 712 | self::getStructuredExceptionData( $e, $catcher ), |
| 713 | $pretty, |
| 714 | $escaping |
| 715 | ); |
| 716 | } |
| 717 | |
| 718 | /** |
| 719 | * Log a throwable to the exception log (if enabled). |
| 720 | * |
| 721 | * This method must not assume the throwable is an MWException, |
| 722 | * it is also used to handle PHP exceptions or exceptions from other libraries. |
| 723 | * |
| 724 | * @since 1.22 |
| 725 | * @param Throwable $e |
| 726 | * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error |
| 727 | * @param array $extraData (since 1.34) Additional data to log |
| 728 | */ |
| 729 | public static function logException( |
| 730 | Throwable $e, |
| 731 | $catcher = self::CAUGHT_BY_OTHER, |
| 732 | $extraData = [] |
| 733 | ) { |
| 734 | if ( !( $e instanceof MWException ) || $e->isLoggable() ) { |
| 735 | $logger = LoggerFactory::getInstance( 'exception' ); |
| 736 | $context = self::getLogContext( $e, $catcher ); |
| 737 | if ( $extraData ) { |
| 738 | $context['extraData'] = $extraData; |
| 739 | } |
| 740 | $logger->error( |
| 741 | self::getLogNormalMessage( $e ), |
| 742 | $context |
| 743 | ); |
| 744 | |
| 745 | $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher ); |
| 746 | if ( $json !== false ) { |
| 747 | $logger = LoggerFactory::getInstance( 'exception-json' ); |
| 748 | $logger->error( $json, [ 'private' => true ] ); |
| 749 | } |
| 750 | |
| 751 | self::callLogExceptionHook( $e, false ); |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | /** |
| 756 | * Log an exception that wasn't thrown but made to wrap an error. |
| 757 | * |
| 758 | * @param ErrorException $e |
| 759 | * @param string $level |
| 760 | * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error |
| 761 | */ |
| 762 | private static function logError( |
| 763 | ErrorException $e, |
| 764 | $level, |
| 765 | $catcher |
| 766 | ) { |
| 767 | // The set_error_handler callback is independent from error_reporting. |
| 768 | $suppressed = ( error_reporting() & $e->getSeverity() ) === 0; |
| 769 | if ( $suppressed ) { |
| 770 | // Instead of discarding these entirely, give some visibility (but only |
| 771 | // when debugging) to errors that were intentionally silenced via |
| 772 | // the error silencing operator (@) or Wikimedia\AtEase. |
| 773 | // To avoid clobbering Logstash results, set the level to DEBUG |
| 774 | // and also send them to a dedicated channel (T193472). |
| 775 | $channel = 'silenced-error'; |
| 776 | $level = LogLevel::DEBUG; |
| 777 | } else { |
| 778 | $channel = 'error'; |
| 779 | } |
| 780 | $logger = LoggerFactory::getInstance( $channel ); |
| 781 | $logger->log( |
| 782 | $level, |
| 783 | self::getLogNormalMessage( $e ), |
| 784 | self::getLogContext( $e, $catcher ) |
| 785 | ); |
| 786 | |
| 787 | self::callLogExceptionHook( $e, $suppressed ); |
| 788 | } |
| 789 | |
| 790 | /** |
| 791 | * Call the LogException hook, suppressing some exceptions. |
| 792 | * |
| 793 | * @param Throwable $e |
| 794 | * @param bool $suppressed |
| 795 | */ |
| 796 | private static function callLogExceptionHook( Throwable $e, bool $suppressed ) { |
| 797 | try { |
| 798 | // It's possible for the exception handler to be triggered during service container |
| 799 | // initialization, e.g. if an autoloaded file triggers deprecation warnings. |
| 800 | // To avoid a difficult-to-debug autoload loop, avoid attempting to initialize the service |
| 801 | // container here. (T380456). |
| 802 | // The exception handler is also triggered when autoloading of HookRunner class fails, |
| 803 | // > Uncaught Error: Class "MediaWiki\HookContainer\HookRunner" not found |
| 804 | // Avoid use of the not-loaded class here, as that override the real error. |
| 805 | if ( !MediaWikiServices::hasInstance() || !class_exists( HookRunner::class, false ) ) { |
| 806 | return; |
| 807 | } |
| 808 | |
| 809 | ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) ) |
| 810 | ->onLogException( $e, $suppressed ); |
| 811 | } catch ( RecursiveServiceDependencyException $e ) { |
| 812 | // An error from the HookContainer wiring will lead here (T379125) |
| 813 | } |
| 814 | } |
| 815 | } |