[ Index ]

PHP Cross Reference of MediaWiki-1.24.0

title

Body

[close]

/includes/objectcache/ -> SqlBagOStuff.php (source)

   1  <?php
   2  /**
   3   * Object caching using a SQL database.
   4   *
   5   * This program is free software; you can redistribute it and/or modify
   6   * it under the terms of the GNU General Public License as published by
   7   * the Free Software Foundation; either version 2 of the License, or
   8   * (at your option) any later version.
   9   *
  10   * This program is distributed in the hope that it will be useful,
  11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13   * GNU General Public License for more details.
  14   *
  15   * You should have received a copy of the GNU General Public License along
  16   * with this program; if not, write to the Free Software Foundation, Inc.,
  17   * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18   * http://www.gnu.org/copyleft/gpl.html
  19   *
  20   * @file
  21   * @ingroup Cache
  22   */
  23  
  24  /**
  25   * Class to store objects in the database
  26   *
  27   * @ingroup Cache
  28   */
  29  class SqlBagOStuff extends BagOStuff {
  30      /** @var LoadBalancer */
  31      protected $lb;
  32  
  33      protected $serverInfos;
  34  
  35      /** @var array */
  36      protected $serverNames;
  37  
  38      /** @var int */
  39      protected $numServers;
  40  
  41      /** @var array */
  42      protected $conns;
  43  
  44      /** @var int */
  45      protected $lastExpireAll = 0;
  46  
  47      /** @var int */
  48      protected $purgePeriod = 100;
  49  
  50      /** @var int */
  51      protected $shards = 1;
  52  
  53      /** @var string */
  54      protected $tableName = 'objectcache';
  55  
  56      /** @var array UNIX timestamps */
  57      protected $connFailureTimes = array();
  58  
  59      /** @var array Exceptions */
  60      protected $connFailureErrors = array();
  61  
  62      /**
  63       * Constructor. Parameters are:
  64       *   - server:      A server info structure in the format required by each
  65       *                  element in $wgDBServers.
  66       *
  67       *   - servers:     An array of server info structures describing a set of
  68       *                  database servers to distribute keys to. If this is
  69       *                  specified, the "server" option will be ignored.
  70       *
  71       *   - purgePeriod: The average number of object cache requests in between
  72       *                  garbage collection operations, where expired entries
  73       *                  are removed from the database. Or in other words, the
  74       *                  reciprocal of the probability of purging on any given
  75       *                  request. If this is set to zero, purging will never be
  76       *                  done.
  77       *
  78       *   - tableName:   The table name to use, default is "objectcache".
  79       *
  80       *   - shards:      The number of tables to use for data storage on each server.
  81       *                  If this is more than 1, table names will be formed in the style
  82       *                  objectcacheNNN where NNN is the shard index, between 0 and
  83       *                  shards-1. The number of digits will be the minimum number
  84       *                  required to hold the largest shard index. Data will be
  85       *                  distributed across all tables by key hash. This is for
  86       *                  MySQL bugs 61735 and 61736.
  87       *
  88       * @param array $params
  89       */
  90  	public function __construct( $params ) {
  91          if ( isset( $params['servers'] ) ) {
  92              $this->serverInfos = $params['servers'];
  93              $this->numServers = count( $this->serverInfos );
  94              $this->serverNames = array();
  95              foreach ( $this->serverInfos as $i => $info ) {
  96                  $this->serverNames[$i] = isset( $info['host'] ) ? $info['host'] : "#$i";
  97              }
  98          } elseif ( isset( $params['server'] ) ) {
  99              $this->serverInfos = array( $params['server'] );
 100              $this->numServers = count( $this->serverInfos );
 101          } else {
 102              $this->serverInfos = false;
 103              $this->numServers = 1;
 104          }
 105          if ( isset( $params['purgePeriod'] ) ) {
 106              $this->purgePeriod = intval( $params['purgePeriod'] );
 107          }
 108          if ( isset( $params['tableName'] ) ) {
 109              $this->tableName = $params['tableName'];
 110          }
 111          if ( isset( $params['shards'] ) ) {
 112              $this->shards = intval( $params['shards'] );
 113          }
 114      }
 115  
 116      /**
 117       * Get a connection to the specified database
 118       *
 119       * @param int $serverIndex
 120       * @return DatabaseBase
 121       */
 122  	protected function getDB( $serverIndex ) {
 123          global $wgDebugDBTransactions;
 124  
 125          if ( !isset( $this->conns[$serverIndex] ) ) {
 126              if ( $serverIndex >= $this->numServers ) {
 127                  throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
 128              }
 129  
 130              # Don't keep timing out trying to connect for each call if the DB is down
 131              if ( isset( $this->connFailureErrors[$serverIndex] )
 132                  && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
 133              ) {
 134                  throw $this->connFailureErrors[$serverIndex];
 135              }
 136  
 137              # If server connection info was given, use that
 138              if ( $this->serverInfos ) {
 139                  if ( $wgDebugDBTransactions ) {
 140                      wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
 141                  }
 142                  $info = $this->serverInfos[$serverIndex];
 143                  $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
 144                  $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
 145                  wfDebug( __CLASS__ . ": connecting to $host\n" );
 146                  $db = DatabaseBase::factory( $type, $info );
 147                  $db->clearFlag( DBO_TRX );
 148              } else {
 149                  /*
 150                   * We must keep a separate connection to MySQL in order to avoid deadlocks
 151                   * However, SQLite has an opposite behavior. And PostgreSQL needs to know
 152                   * if we are in transaction or no
 153                   */
 154                  if ( wfGetDB( DB_MASTER )->getType() == 'mysql' ) {
 155                      $this->lb = wfGetLBFactory()->newMainLB();
 156                      $db = $this->lb->getConnection( DB_MASTER );
 157                      $db->clearFlag( DBO_TRX ); // auto-commit mode
 158                  } else {
 159                      $db = wfGetDB( DB_MASTER );
 160                  }
 161              }
 162              if ( $wgDebugDBTransactions ) {
 163                  wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
 164              }
 165              $this->conns[$serverIndex] = $db;
 166          }
 167  
 168          return $this->conns[$serverIndex];
 169      }
 170  
 171      /**
 172       * Get the server index and table name for a given key
 173       * @param string $key
 174       * @return array Server index and table name
 175       */
 176  	protected function getTableByKey( $key ) {
 177          if ( $this->shards > 1 ) {
 178              $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
 179              $tableIndex = $hash % $this->shards;
 180          } else {
 181              $tableIndex = 0;
 182          }
 183          if ( $this->numServers > 1 ) {
 184              $sortedServers = $this->serverNames;
 185              ArrayUtils::consistentHashSort( $sortedServers, $key );
 186              reset( $sortedServers );
 187              $serverIndex = key( $sortedServers );
 188          } else {
 189              $serverIndex = 0;
 190          }
 191          return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
 192      }
 193  
 194      /**
 195       * Get the table name for a given shard index
 196       * @param int $index
 197       * @return string
 198       */
 199  	protected function getTableNameByShard( $index ) {
 200          if ( $this->shards > 1 ) {
 201              $decimals = strlen( $this->shards - 1 );
 202              return $this->tableName .
 203                  sprintf( "%0{$decimals}d", $index );
 204          } else {
 205              return $this->tableName;
 206          }
 207      }
 208  
 209      /**
 210       * @param string $key
 211       * @param mixed $casToken [optional]
 212       * @return mixed
 213       */
 214  	public function get( $key, &$casToken = null ) {
 215          $values = $this->getMulti( array( $key ) );
 216          if ( array_key_exists( $key, $values ) ) {
 217              $casToken = $values[$key];
 218              return $values[$key];
 219          }
 220          return false;
 221      }
 222  
 223      /**
 224       * @param array $keys
 225       * @return array
 226       */
 227  	public function getMulti( array $keys ) {
 228          $values = array(); // array of (key => value)
 229  
 230          $keysByTable = array();
 231          foreach ( $keys as $key ) {
 232              list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
 233              $keysByTable[$serverIndex][$tableName][] = $key;
 234          }
 235  
 236          $this->garbageCollect(); // expire old entries if any
 237  
 238          $dataRows = array();
 239          foreach ( $keysByTable as $serverIndex => $serverKeys ) {
 240              try {
 241                  $db = $this->getDB( $serverIndex );
 242                  foreach ( $serverKeys as $tableName => $tableKeys ) {
 243                      $res = $db->select( $tableName,
 244                          array( 'keyname', 'value', 'exptime' ),
 245                          array( 'keyname' => $tableKeys ),
 246                          __METHOD__,
 247                          // Approximate write-on-the-fly BagOStuff API via blocking.
 248                          // This approximation fails if a ROLLBACK happens (which is rare).
 249                          // We do not want to flush the TRX as that can break callers.
 250                          $db->trxLevel() ? array( 'LOCK IN SHARE MODE' ) : array()
 251                      );
 252                      if ( $res === false ) {
 253                          continue;
 254                      }
 255                      foreach ( $res as $row ) {
 256                          $row->serverIndex = $serverIndex;
 257                          $row->tableName = $tableName;
 258                          $dataRows[$row->keyname] = $row;
 259                      }
 260                  }
 261              } catch ( DBError $e ) {
 262                  $this->handleReadError( $e, $serverIndex );
 263              }
 264          }
 265  
 266          foreach ( $keys as $key ) {
 267              if ( isset( $dataRows[$key] ) ) { // HIT?
 268                  $row = $dataRows[$key];
 269                  $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
 270                  try {
 271                      $db = $this->getDB( $row->serverIndex );
 272                      if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
 273                          $this->debug( "get: key has expired, deleting" );
 274                          # Put the expiry time in the WHERE condition to avoid deleting a
 275                          # newly-inserted value
 276                          $db->delete( $row->tableName,
 277                              array( 'keyname' => $key, 'exptime' => $row->exptime ),
 278                              __METHOD__ );
 279                      } else { // HIT
 280                          $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
 281                      }
 282                  } catch ( DBQueryError $e ) {
 283                      $this->handleWriteError( $e, $row->serverIndex );
 284                  }
 285              } else { // MISS
 286                  $this->debug( 'get: no matching rows' );
 287              }
 288          }
 289  
 290          return $values;
 291      }
 292  
 293      /**
 294       * @param array $data
 295       * @param int $expiry
 296       * @return bool
 297       */
 298  	public function setMulti( array $data, $expiry = 0 ) {
 299          $keysByTable = array();
 300          foreach ( $data as $key => $value ) {
 301              list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
 302              $keysByTable[$serverIndex][$tableName][] = $key;
 303          }
 304  
 305          $this->garbageCollect(); // expire old entries if any
 306  
 307          $result = true;
 308          $exptime = (int)$expiry;
 309          foreach ( $keysByTable as $serverIndex => $serverKeys ) {
 310              try {
 311                  $db = $this->getDB( $serverIndex );
 312              } catch ( DBError $e ) {
 313                  $this->handleWriteError( $e, $serverIndex );
 314                  $result = false;
 315                  continue;
 316              }
 317  
 318              if ( $exptime < 0 ) {
 319                  $exptime = 0;
 320              }
 321  
 322              if ( $exptime == 0 ) {
 323                  $encExpiry = $this->getMaxDateTime( $db );
 324              } else {
 325                  if ( $exptime < 3.16e8 ) { # ~10 years
 326                      $exptime += time();
 327                  }
 328                  $encExpiry = $db->timestamp( $exptime );
 329              }
 330              foreach ( $serverKeys as $tableName => $tableKeys ) {
 331                  $rows = array();
 332                  foreach ( $tableKeys as $key ) {
 333                      $rows[] = array(
 334                          'keyname' => $key,
 335                          'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
 336                          'exptime' => $encExpiry,
 337                      );
 338                  }
 339  
 340                  try {
 341                      $db->replace(
 342                          $tableName,
 343                          array( 'keyname' ),
 344                          $rows,
 345                          __METHOD__
 346                      );
 347                  } catch ( DBError $e ) {
 348                      $this->handleWriteError( $e, $serverIndex );
 349                      $result = false;
 350                  }
 351  
 352              }
 353  
 354          }
 355  
 356          return $result;
 357      }
 358  
 359  
 360  
 361      /**
 362       * @param string $key
 363       * @param mixed $value
 364       * @param int $exptime
 365       * @return bool
 366       */
 367  	public function set( $key, $value, $exptime = 0 ) {
 368          list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
 369          try {
 370              $db = $this->getDB( $serverIndex );
 371              $exptime = intval( $exptime );
 372  
 373              if ( $exptime < 0 ) {
 374                  $exptime = 0;
 375              }
 376  
 377              if ( $exptime == 0 ) {
 378                  $encExpiry = $this->getMaxDateTime( $db );
 379              } else {
 380                  if ( $exptime < 3.16e8 ) { # ~10 years
 381                      $exptime += time();
 382                  }
 383  
 384                  $encExpiry = $db->timestamp( $exptime );
 385              }
 386              // (bug 24425) use a replace if the db supports it instead of
 387              // delete/insert to avoid clashes with conflicting keynames
 388              $db->replace(
 389                  $tableName,
 390                  array( 'keyname' ),
 391                  array(
 392                      'keyname' => $key,
 393                      'value' => $db->encodeBlob( $this->serialize( $value ) ),
 394                      'exptime' => $encExpiry
 395                  ), __METHOD__ );
 396          } catch ( DBError $e ) {
 397              $this->handleWriteError( $e, $serverIndex );
 398              return false;
 399          }
 400  
 401          return true;
 402      }
 403  
 404      /**
 405       * @param mixed $casToken
 406       * @param string $key
 407       * @param mixed $value
 408       * @param int $exptime
 409       * @return bool
 410       */
 411  	public function cas( $casToken, $key, $value, $exptime = 0 ) {
 412          list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
 413          try {
 414              $db = $this->getDB( $serverIndex );
 415              $exptime = intval( $exptime );
 416  
 417              if ( $exptime < 0 ) {
 418                  $exptime = 0;
 419              }
 420  
 421              if ( $exptime == 0 ) {
 422                  $encExpiry = $this->getMaxDateTime( $db );
 423              } else {
 424                  if ( $exptime < 3.16e8 ) { # ~10 years
 425                      $exptime += time();
 426                  }
 427                  $encExpiry = $db->timestamp( $exptime );
 428              }
 429              // (bug 24425) use a replace if the db supports it instead of
 430              // delete/insert to avoid clashes with conflicting keynames
 431              $db->update(
 432                  $tableName,
 433                  array(
 434                      'keyname' => $key,
 435                      'value' => $db->encodeBlob( $this->serialize( $value ) ),
 436                      'exptime' => $encExpiry
 437                  ),
 438                  array(
 439                      'keyname' => $key,
 440                      'value' => $db->encodeBlob( $this->serialize( $casToken ) )
 441                  ),
 442                  __METHOD__
 443              );
 444          } catch ( DBQueryError $e ) {
 445              $this->handleWriteError( $e, $serverIndex );
 446  
 447              return false;
 448          }
 449  
 450          return (bool)$db->affectedRows();
 451      }
 452  
 453      /**
 454       * @param string $key
 455       * @param int $time
 456       * @return bool
 457       */
 458  	public function delete( $key, $time = 0 ) {
 459          list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
 460          try {
 461              $db = $this->getDB( $serverIndex );
 462              $db->delete(
 463                  $tableName,
 464                  array( 'keyname' => $key ),
 465                  __METHOD__ );
 466          } catch ( DBError $e ) {
 467              $this->handleWriteError( $e, $serverIndex );
 468              return false;
 469          }
 470  
 471          return true;
 472      }
 473  
 474      /**
 475       * @param string $key
 476       * @param int $step
 477       * @return int|null
 478       */
 479  	public function incr( $key, $step = 1 ) {
 480          list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
 481          try {
 482              $db = $this->getDB( $serverIndex );
 483              $step = intval( $step );
 484              $row = $db->selectRow(
 485                  $tableName,
 486                  array( 'value', 'exptime' ),
 487                  array( 'keyname' => $key ),
 488                  __METHOD__,
 489                  array( 'FOR UPDATE' ) );
 490              if ( $row === false ) {
 491                  // Missing
 492  
 493                  return null;
 494              }
 495              $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
 496              if ( $this->isExpired( $db, $row->exptime ) ) {
 497                  // Expired, do not reinsert
 498  
 499                  return null;
 500              }
 501  
 502              $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
 503              $newValue = $oldValue + $step;
 504              $db->insert( $tableName,
 505                  array(
 506                      'keyname' => $key,
 507                      'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
 508                      'exptime' => $row->exptime
 509                  ), __METHOD__, 'IGNORE' );
 510  
 511              if ( $db->affectedRows() == 0 ) {
 512                  // Race condition. See bug 28611
 513                  $newValue = null;
 514              }
 515          } catch ( DBError $e ) {
 516              $this->handleWriteError( $e, $serverIndex );
 517              return null;
 518          }
 519  
 520          return $newValue;
 521      }
 522  
 523      /**
 524       * @param DatabaseBase $db
 525       * @param string $exptime
 526       * @return bool
 527       */
 528  	protected function isExpired( $db, $exptime ) {
 529          return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
 530      }
 531  
 532      /**
 533       * @param DatabaseBase $db
 534       * @return string
 535       */
 536  	protected function getMaxDateTime( $db ) {
 537          if ( time() > 0x7fffffff ) {
 538              return $db->timestamp( 1 << 62 );
 539          } else {
 540              return $db->timestamp( 0x7fffffff );
 541          }
 542      }
 543  
 544  	protected function garbageCollect() {
 545          if ( !$this->purgePeriod ) {
 546              // Disabled
 547              return;
 548          }
 549          // Only purge on one in every $this->purgePeriod requests.
 550          if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
 551              return;
 552          }
 553          $now = time();
 554          // Avoid repeating the delete within a few seconds
 555          if ( $now > ( $this->lastExpireAll + 1 ) ) {
 556              $this->lastExpireAll = $now;
 557              $this->expireAll();
 558          }
 559      }
 560  
 561  	public function expireAll() {
 562          $this->deleteObjectsExpiringBefore( wfTimestampNow() );
 563      }
 564  
 565      /**
 566       * Delete objects from the database which expire before a certain date.
 567       * @param string $timestamp
 568       * @param bool|callable $progressCallback
 569       * @return bool
 570       */
 571  	public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
 572          for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
 573              try {
 574                  $db = $this->getDB( $serverIndex );
 575                  $dbTimestamp = $db->timestamp( $timestamp );
 576                  $totalSeconds = false;
 577                  $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
 578                  for ( $i = 0; $i < $this->shards; $i++ ) {
 579                      $maxExpTime = false;
 580                      while ( true ) {
 581                          $conds = $baseConds;
 582                          if ( $maxExpTime !== false ) {
 583                              $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
 584                          }
 585                          $rows = $db->select(
 586                              $this->getTableNameByShard( $i ),
 587                              array( 'keyname', 'exptime' ),
 588                              $conds,
 589                              __METHOD__,
 590                              array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
 591                          if ( $rows === false || !$rows->numRows() ) {
 592                              break;
 593                          }
 594                          $keys = array();
 595                          $row = $rows->current();
 596                          $minExpTime = $row->exptime;
 597                          if ( $totalSeconds === false ) {
 598                              $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
 599                                  - wfTimestamp( TS_UNIX, $minExpTime );
 600                          }
 601                          foreach ( $rows as $row ) {
 602                              $keys[] = $row->keyname;
 603                              $maxExpTime = $row->exptime;
 604                          }
 605  
 606                          $db->delete(
 607                              $this->getTableNameByShard( $i ),
 608                              array(
 609                                  'exptime >= ' . $db->addQuotes( $minExpTime ),
 610                                  'exptime < ' . $db->addQuotes( $dbTimestamp ),
 611                                  'keyname' => $keys
 612                              ),
 613                              __METHOD__ );
 614  
 615                          if ( $progressCallback ) {
 616                              if ( intval( $totalSeconds ) === 0 ) {
 617                                  $percent = 0;
 618                              } else {
 619                                  $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
 620                                      - wfTimestamp( TS_UNIX, $maxExpTime );
 621                                  if ( $remainingSeconds > $totalSeconds ) {
 622                                      $totalSeconds = $remainingSeconds;
 623                                  }
 624                                  $percent = ( $i + $remainingSeconds / $totalSeconds )
 625                                      / $this->shards * 100;
 626                              }
 627                              $percent = ( $percent / $this->numServers )
 628                                  + ( $serverIndex / $this->numServers * 100 );
 629                              call_user_func( $progressCallback, $percent );
 630                          }
 631                      }
 632                  }
 633              } catch ( DBError $e ) {
 634                  $this->handleWriteError( $e, $serverIndex );
 635                  return false;
 636              }
 637          }
 638          return true;
 639      }
 640  
 641  	public function deleteAll() {
 642          for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
 643              try {
 644                  $db = $this->getDB( $serverIndex );
 645                  for ( $i = 0; $i < $this->shards; $i++ ) {
 646                      $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
 647                  }
 648              } catch ( DBError $e ) {
 649                  $this->handleWriteError( $e, $serverIndex );
 650                  return false;
 651              }
 652          }
 653          return true;
 654      }
 655  
 656      /**
 657       * Serialize an object and, if possible, compress the representation.
 658       * On typical message and page data, this can provide a 3X decrease
 659       * in storage requirements.
 660       *
 661       * @param mixed $data
 662       * @return string
 663       */
 664  	protected function serialize( &$data ) {
 665          $serial = serialize( $data );
 666  
 667          if ( function_exists( 'gzdeflate' ) ) {
 668              return gzdeflate( $serial );
 669          } else {
 670              return $serial;
 671          }
 672      }
 673  
 674      /**
 675       * Unserialize and, if necessary, decompress an object.
 676       * @param string $serial
 677       * @return mixed
 678       */
 679  	protected function unserialize( $serial ) {
 680          if ( function_exists( 'gzinflate' ) ) {
 681              wfSuppressWarnings();
 682              $decomp = gzinflate( $serial );
 683              wfRestoreWarnings();
 684  
 685              if ( false !== $decomp ) {
 686                  $serial = $decomp;
 687              }
 688          }
 689  
 690          $ret = unserialize( $serial );
 691  
 692          return $ret;
 693      }
 694  
 695      /**
 696       * Handle a DBError which occurred during a read operation.
 697       *
 698       * @param DBError $exception
 699       * @param int $serverIndex
 700       */
 701  	protected function handleReadError( DBError $exception, $serverIndex ) {
 702          if ( $exception instanceof DBConnectionError ) {
 703              $this->markServerDown( $exception, $serverIndex );
 704          }
 705          wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
 706          if ( $exception instanceof DBConnectionError ) {
 707              $this->setLastError( BagOStuff::ERR_UNREACHABLE );
 708              wfDebug( __METHOD__ . ": ignoring connection error\n" );
 709          } else {
 710              $this->setLastError( BagOStuff::ERR_UNEXPECTED );
 711              wfDebug( __METHOD__ . ": ignoring query error\n" );
 712          }
 713      }
 714  
 715      /**
 716       * Handle a DBQueryError which occurred during a write operation.
 717       *
 718       * @param DBError $exception
 719       * @param int $serverIndex
 720       */
 721  	protected function handleWriteError( DBError $exception, $serverIndex ) {
 722          if ( $exception instanceof DBConnectionError ) {
 723              $this->markServerDown( $exception, $serverIndex );
 724          }
 725          if ( $exception->db && $exception->db->wasReadOnlyError() ) {
 726              try {
 727                  $exception->db->rollback( __METHOD__ );
 728              } catch ( DBError $e ) {
 729              }
 730          }
 731          wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
 732          if ( $exception instanceof DBConnectionError ) {
 733              $this->setLastError( BagOStuff::ERR_UNREACHABLE );
 734              wfDebug( __METHOD__ . ": ignoring connection error\n" );
 735          } else {
 736              $this->setLastError( BagOStuff::ERR_UNEXPECTED );
 737              wfDebug( __METHOD__ . ": ignoring query error\n" );
 738          }
 739      }
 740  
 741      /**
 742       * Mark a server down due to a DBConnectionError exception
 743       *
 744       * @param DBError $exception
 745       * @param int $serverIndex
 746       */
 747  	protected function markServerDown( $exception, $serverIndex ) {
 748          if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
 749              if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
 750                  unset( $this->connFailureTimes[$serverIndex] );
 751                  unset( $this->connFailureErrors[$serverIndex] );
 752              } else {
 753                  wfDebug( __METHOD__ . ": Server #$serverIndex already down\n" );
 754                  return;
 755              }
 756          }
 757          $now = time();
 758          wfDebug( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) . "\n" );
 759          $this->connFailureTimes[$serverIndex] = $now;
 760          $this->connFailureErrors[$serverIndex] = $exception;
 761      }
 762  
 763      /**
 764       * Create shard tables. For use from eval.php.
 765       */
 766  	public function createTables() {
 767          for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
 768              $db = $this->getDB( $serverIndex );
 769              if ( $db->getType() !== 'mysql' ) {
 770                  throw new MWException( __METHOD__ . ' is not supported on this DB server' );
 771              }
 772  
 773              for ( $i = 0; $i < $this->shards; $i++ ) {
 774                  $db->query(
 775                      'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
 776                      ' LIKE ' . $db->tableName( 'objectcache' ),
 777                      __METHOD__ );
 778              }
 779          }
 780      }
 781  }
 782  
 783  /**
 784   * Backwards compatibility alias
 785   */
 786  class MediaWikiBagOStuff extends SqlBagOStuff {
 787  }


Generated: Fri Nov 28 14:03:12 2014 Cross-referenced by PHPXref 0.7.1