MediaWiki  master
SqlBagOStuff.php
Go to the documentation of this file.
1 <?php
33 
39 class SqlBagOStuff extends BagOStuff {
41  protected $serverInfos;
43  protected $serverTags;
45  protected $numServers;
47  protected $lastGarbageCollect = 0;
49  protected $purgePeriod = 10;
51  protected $purgeLimit = 100;
53  protected $shards = 1;
55  protected $tableName = 'objectcache';
57  protected $replicaOnly = false;
59  protected $syncTimeout = 3;
60 
62  protected $separateMainLB;
64  protected $conns;
66  protected $connFailureTimes = [];
68  protected $connFailureErrors = [];
69 
71  private static $GARBAGE_COLLECT_DELAY_SEC = 1;
72 
74  private static $OP_SET = 'set';
76  private static $OP_ADD = 'add';
78  private static $OP_TOUCH = 'touch';
80  private static $OP_DELETE = 'delete';
81 
121  public function __construct( $params ) {
122  parent::__construct( $params );
123 
124  $this->attrMap[self::ATTR_EMULATION] = self::QOS_EMULATION_SQL;
125  $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
126 
127  if ( isset( $params['servers'] ) ) {
128  $this->serverInfos = [];
129  $this->serverTags = [];
130  $this->numServers = count( $params['servers'] );
131  $index = 0;
132  foreach ( $params['servers'] as $tag => $info ) {
133  $this->serverInfos[$index] = $info;
134  if ( is_string( $tag ) ) {
135  $this->serverTags[$index] = $tag;
136  } else {
137  $this->serverTags[$index] = $info['host'] ?? "#$index";
138  }
139  ++$index;
140  }
141  } elseif ( isset( $params['server'] ) ) {
142  $this->serverInfos = [ $params['server'] ];
143  $this->numServers = count( $this->serverInfos );
144  } else {
145  // Default to using the main wiki's database servers
146  $this->serverInfos = false;
147  $this->numServers = 1;
148  $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
149  }
150  if ( isset( $params['purgePeriod'] ) ) {
151  $this->purgePeriod = intval( $params['purgePeriod'] );
152  }
153  if ( isset( $params['purgeLimit'] ) ) {
154  $this->purgeLimit = intval( $params['purgeLimit'] );
155  }
156  if ( isset( $params['tableName'] ) ) {
157  $this->tableName = $params['tableName'];
158  }
159  if ( isset( $params['shards'] ) ) {
160  $this->shards = intval( $params['shards'] );
161  }
162  if ( isset( $params['syncTimeout'] ) ) {
163  $this->syncTimeout = $params['syncTimeout'];
164  }
165  // Backwards-compatibility for < 1.34
166  $this->replicaOnly = $params['replicaOnly'] ?? ( $params['slaveOnly'] ?? false );
167  }
168 
176  protected function getDB( $serverIndex ) {
177  if ( $serverIndex >= $this->numServers ) {
178  throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
179  }
180 
181  # Don't keep timing out trying to connect for each call if the DB is down
182  if (
183  isset( $this->connFailureErrors[$serverIndex] ) &&
184  ( time() - $this->connFailureTimes[$serverIndex] ) < 60
185  ) {
186  throw $this->connFailureErrors[$serverIndex];
187  }
188 
189  if ( $this->serverInfos ) {
190  if ( !isset( $this->conns[$serverIndex] ) ) {
191  // Use custom database defined by server connection info
192  $info = $this->serverInfos[$serverIndex];
193  $type = $info['type'] ?? 'mysql';
194  $host = $info['host'] ?? '[unknown]';
195  $this->logger->debug( __CLASS__ . ": connecting to $host" );
196  $db = Database::factory( $type, $info );
197  $db->clearFlag( DBO_TRX ); // auto-commit mode
198  $this->conns[$serverIndex] = $db;
199  }
200  $db = $this->conns[$serverIndex];
201  } else {
202  // Use the main LB database
203  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
204  $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
205  if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
206  // Keep a separate connection to avoid contention and deadlocks
207  $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
208  } else {
209  // However, SQLite has the opposite behavior due to DB-level locking.
210  // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
211  $db = $lb->getConnection( $index );
212  }
213  }
214 
215  $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
216 
217  return $db;
218  }
219 
225  protected function getTableByKey( $key ) {
226  if ( $this->shards > 1 ) {
227  $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
228  $tableIndex = $hash % $this->shards;
229  } else {
230  $tableIndex = 0;
231  }
232  if ( $this->numServers > 1 ) {
233  $sortedServers = $this->serverTags;
234  ArrayUtils::consistentHashSort( $sortedServers, $key );
235  reset( $sortedServers );
236  $serverIndex = key( $sortedServers );
237  } else {
238  $serverIndex = 0;
239  }
240  return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
241  }
242 
248  protected function getTableNameByShard( $index ) {
249  if ( $this->shards > 1 ) {
250  $decimals = strlen( $this->shards - 1 );
251  return $this->tableName .
252  sprintf( "%0{$decimals}d", $index );
253  } else {
254  return $this->tableName;
255  }
256  }
257 
258  protected function doGet( $key, $flags = 0, &$casToken = null ) {
259  $casToken = null;
260 
261  $blobs = $this->fetchBlobMulti( [ $key ] );
262  if ( array_key_exists( $key, $blobs ) ) {
263  $blob = $blobs[$key];
264  $value = $this->unserialize( $blob );
265 
266  $casToken = ( $value !== false ) ? $blob : null;
267 
268  return $value;
269  }
270 
271  return false;
272  }
273 
274  protected function doGetMulti( array $keys, $flags = 0 ) {
275  $values = [];
276 
277  $blobs = $this->fetchBlobMulti( $keys );
278  foreach ( $blobs as $key => $blob ) {
279  $values[$key] = $this->unserialize( $blob );
280  }
281 
282  return $values;
283  }
284 
285  protected function fetchBlobMulti( array $keys, $flags = 0 ) {
286  $values = []; // array of (key => value)
287 
288  $keysByTable = [];
289  foreach ( $keys as $key ) {
290  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
291  $keysByTable[$serverIndex][$tableName][] = $key;
292  }
293 
294  $dataRows = [];
295  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
296  try {
297  $db = $this->getDB( $serverIndex );
298  foreach ( $serverKeys as $tableName => $tableKeys ) {
299  $res = $db->select( $tableName,
300  [ 'keyname', 'value', 'exptime' ],
301  [ 'keyname' => $tableKeys ],
302  __METHOD__,
303  // Approximate write-on-the-fly BagOStuff API via blocking.
304  // This approximation fails if a ROLLBACK happens (which is rare).
305  // We do not want to flush the TRX as that can break callers.
306  $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
307  );
308  if ( $res === false ) {
309  continue;
310  }
311  foreach ( $res as $row ) {
312  $row->serverIndex = $serverIndex;
313  $row->tableName = $tableName;
314  $dataRows[$row->keyname] = $row;
315  }
316  }
317  } catch ( DBError $e ) {
318  $this->handleReadError( $e, $serverIndex );
319  }
320  }
321 
322  foreach ( $keys as $key ) {
323  if ( isset( $dataRows[$key] ) ) { // HIT?
324  $row = $dataRows[$key];
325  $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
326  $db = null; // in case of connection failure
327  try {
328  $db = $this->getDB( $row->serverIndex );
329  if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
330  $this->debug( "get: key has expired" );
331  } else { // HIT
332  $values[$key] = $db->decodeBlob( $row->value );
333  }
334  } catch ( DBQueryError $e ) {
335  $this->handleWriteError( $e, $db, $row->serverIndex );
336  }
337  } else { // MISS
338  $this->debug( 'get: no matching rows' );
339  }
340  }
341 
342  return $values;
343  }
344 
345  protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
346  return $this->modifyMulti( $data, $exptime, $flags, self::$OP_SET );
347  }
348 
356  private function modifyMulti( array $data, $exptime, $flags, $op ) {
357  $keysByTable = [];
358  foreach ( $data as $key => $value ) {
359  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
360  $keysByTable[$serverIndex][$tableName][] = $key;
361  }
362 
363  $exptime = $this->convertToExpiry( $exptime );
364 
365  $result = true;
367  $silenceScope = $this->silenceTransactionProfiler();
368  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
369  $db = null; // in case of connection failure
370  try {
371  $db = $this->getDB( $serverIndex );
372  $this->occasionallyGarbageCollect( $db ); // expire old entries if any
373  $dbExpiry = $exptime ? $db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
374  } catch ( DBError $e ) {
375  $this->handleWriteError( $e, $db, $serverIndex );
376  $result = false;
377  continue;
378  }
379 
380  foreach ( $serverKeys as $tableName => $tableKeys ) {
381  try {
382  $result = $this->updateTableKeys(
383  $op,
384  $db,
385  $tableName,
386  $tableKeys,
387  $data,
388  $dbExpiry
389  ) && $result;
390  } catch ( DBError $e ) {
391  $this->handleWriteError( $e, $db, $serverIndex );
392  $result = false;
393  }
394 
395  }
396  }
397 
398  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
399  $result = $this->waitForReplication() && $result;
400  }
401 
402  return $result;
403  }
404 
416  private function updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
417  $success = true;
418 
419  if ( $op === self::$OP_ADD ) {
420  $rows = [];
421  foreach ( $tableKeys as $key ) {
422  $rows[] = [
423  'keyname' => $key,
424  'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
425  'exptime' => $dbExpiry
426  ];
427  }
428  $db->delete(
429  $table,
430  [
431  'keyname' => $tableKeys,
432  'exptime <= ' . $db->addQuotes( $db->timestamp() )
433  ],
434  __METHOD__
435  );
436  $db->insert( $table, $rows, __METHOD__, [ 'IGNORE' ] );
437 
438  $success = ( $db->affectedRows() == count( $rows ) );
439  } elseif ( $op === self::$OP_SET ) {
440  $rows = [];
441  foreach ( $tableKeys as $key ) {
442  $rows[] = [
443  'keyname' => $key,
444  'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
445  'exptime' => $dbExpiry
446  ];
447  }
448  $db->replace( $table, [ 'keyname' ], $rows, __METHOD__ );
449  } elseif ( $op === self::$OP_DELETE ) {
450  $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__ );
451  } elseif ( $op === self::$OP_TOUCH ) {
452  $db->update(
453  $table,
454  [ 'exptime' => $dbExpiry ],
455  [
456  'keyname' => $tableKeys,
457  'exptime > ' . $db->addQuotes( $db->timestamp() )
458  ],
459  __METHOD__
460  );
461 
462  $success = ( $db->affectedRows() == count( $tableKeys ) );
463  } else {
464  throw new InvalidArgumentException( "Invalid operation '$op'" );
465  }
466 
467  return $success;
468  }
469 
470  protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
471  return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_SET );
472  }
473 
474  public function add( $key, $value, $exptime = 0, $flags = 0 ) {
475  return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_ADD );
476  }
477 
478  protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
479  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
480  $exptime = $this->convertToExpiry( $exptime );
481 
483  $silenceScope = $this->silenceTransactionProfiler();
484  $db = null; // in case of connection failure
485  try {
486  $db = $this->getDB( $serverIndex );
487  // (T26425) use a replace if the db supports it instead of
488  // delete/insert to avoid clashes with conflicting keynames
489  $db->update(
490  $tableName,
491  [
492  'keyname' => $key,
493  'value' => $db->encodeBlob( $this->serialize( $value ) ),
494  'exptime' => $exptime
495  ? $db->timestamp( $exptime )
496  : $this->getMaxDateTime( $db )
497  ],
498  [
499  'keyname' => $key,
500  'value' => $db->encodeBlob( $casToken ),
501  'exptime > ' . $db->addQuotes( $db->timestamp() )
502  ],
503  __METHOD__
504  );
505  } catch ( DBQueryError $e ) {
506  $this->handleWriteError( $e, $db, $serverIndex );
507 
508  return false;
509  }
510 
511  return (bool)$db->affectedRows();
512  }
513 
514  protected function doDeleteMulti( array $keys, $flags = 0 ) {
515  return $this->modifyMulti(
516  array_fill_keys( $keys, null ),
517  0,
518  $flags,
519  self::$OP_DELETE
520  );
521  }
522 
523  protected function doDelete( $key, $flags = 0 ) {
524  return $this->modifyMulti( [ $key => null ], 0, $flags, self::$OP_DELETE );
525  }
526 
527  public function incr( $key, $step = 1 ) {
528  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
529 
530  $newCount = false;
532  $silenceScope = $this->silenceTransactionProfiler();
533  $db = null; // in case of connection failure
534  try {
535  $db = $this->getDB( $serverIndex );
536  $encTimestamp = $db->addQuotes( $db->timestamp() );
537  $db->update(
538  $tableName,
539  [ 'value = value + ' . (int)$step ],
540  [ 'keyname' => $key, "exptime > $encTimestamp" ],
541  __METHOD__
542  );
543  if ( $db->affectedRows() > 0 ) {
544  $newValue = $db->selectField(
545  $tableName,
546  'value',
547  [ 'keyname' => $key, "exptime > $encTimestamp" ],
548  __METHOD__
549  );
550  if ( $this->isInteger( $newValue ) ) {
551  $newCount = (int)$newValue;
552  }
553  }
554  } catch ( DBError $e ) {
555  $this->handleWriteError( $e, $db, $serverIndex );
556  }
557 
558  return $newCount;
559  }
560 
561  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
562  $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
563  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
564  $ok = $this->waitForReplication() && $ok;
565  }
566 
567  return $ok;
568  }
569 
570  protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
571  return $this->modifyMulti(
572  array_fill_keys( $keys, null ),
573  $exptime,
574  $flags,
575  self::$OP_TOUCH
576  );
577  }
578 
579  protected function doChangeTTL( $key, $exptime, $flags ) {
580  return $this->modifyMulti( [ $key => null ], $exptime, $flags, self::$OP_TOUCH );
581  }
582 
588  protected function isExpired( $db, $exptime ) {
589  return (
590  $exptime != $this->getMaxDateTime( $db ) &&
591  wfTimestamp( TS_UNIX, $exptime ) < time()
592  );
593  }
594 
599  protected function getMaxDateTime( $db ) {
600  if ( time() > 0x7fffffff ) {
601  return $db->timestamp( 1 << 62 );
602  } else {
603  return $db->timestamp( 0x7fffffff );
604  }
605  }
606 
611  protected function occasionallyGarbageCollect( IDatabase $db ) {
612  if (
613  // Random purging is enabled
614  $this->purgePeriod &&
615  // Only purge on one in every $this->purgePeriod writes
616  mt_rand( 0, $this->purgePeriod - 1 ) == 0 &&
617  // Avoid repeating the delete within a few seconds
618  ( time() - $this->lastGarbageCollect ) > self::$GARBAGE_COLLECT_DELAY_SEC
619  ) {
620  $garbageCollector = function () use ( $db ) {
621  $this->deleteServerObjectsExpiringBefore( $db, time(), null, $this->purgeLimit );
622  $this->lastGarbageCollect = time();
623  };
624  if ( $this->asyncHandler ) {
625  $this->lastGarbageCollect = time(); // avoid duplicate enqueues
626  ( $this->asyncHandler )( $garbageCollector );
627  } else {
628  $garbageCollector();
629  }
630  }
631  }
632 
633  public function expireAll() {
634  $this->deleteObjectsExpiringBefore( time() );
635  }
636 
638  $timestamp,
639  callable $progress = null,
640  $limit = INF
641  ) {
643  $silenceScope = $this->silenceTransactionProfiler();
644 
645  $serverIndexes = range( 0, $this->numServers - 1 );
646  shuffle( $serverIndexes );
647 
648  $ok = true;
649 
650  $keysDeletedCount = 0;
651  foreach ( $serverIndexes as $numServersDone => $serverIndex ) {
652  $db = null; // in case of connection failure
653  try {
654  $db = $this->getDB( $serverIndex );
656  $db,
657  $timestamp,
658  $progress,
659  $limit,
660  $numServersDone,
661  $keysDeletedCount
662  );
663  } catch ( DBError $e ) {
664  $this->handleWriteError( $e, $db, $serverIndex );
665  $ok = false;
666  }
667  }
668 
669  return $ok;
670  }
671 
682  IDatabase $db,
683  $timestamp,
684  $progressCallback,
685  $limit,
686  $serversDoneCount = 0,
687  &$keysDeletedCount = 0
688  ) {
689  $cutoffUnix = wfTimestamp( TS_UNIX, $timestamp );
690  $shardIndexes = range( 0, $this->shards - 1 );
691  shuffle( $shardIndexes );
692 
693  foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
694  $continue = null; // last exptime
695  $lag = null; // purge lag
696  do {
697  $res = $db->select(
698  $this->getTableNameByShard( $shardIndex ),
699  [ 'keyname', 'exptime' ],
700  array_merge(
701  [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
702  $continue ? [ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
703  ),
704  __METHOD__,
705  [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
706  );
707 
708  if ( $res->numRows() ) {
709  $row = $res->current();
710  if ( $lag === null ) {
711  $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX, $row->exptime ), 1 );
712  }
713 
714  $keys = [];
715  foreach ( $res as $row ) {
716  $keys[] = $row->keyname;
717  $continue = $row->exptime;
718  }
719 
720  $db->delete(
721  $this->getTableNameByShard( $shardIndex ),
722  [
723  'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
724  'keyname' => $keys
725  ],
726  __METHOD__
727  );
728  $keysDeletedCount += $db->affectedRows();
729  }
730 
731  if ( is_callable( $progressCallback ) ) {
732  if ( $lag ) {
733  $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX, $continue );
734  $processedLag = max( $lag - $remainingLag, 0 );
735  $doneRatio = ( $numShardsDone + $processedLag / $lag ) / $this->shards;
736  } else {
737  $doneRatio = 1;
738  }
739 
740  $overallRatio = ( $doneRatio / $this->numServers )
741  + ( $serversDoneCount / $this->numServers );
742  call_user_func( $progressCallback, $overallRatio * 100 );
743  }
744  } while ( $res->numRows() && $keysDeletedCount < $limit );
745  }
746  }
747 
753  public function deleteAll() {
755  $silenceScope = $this->silenceTransactionProfiler();
756  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
757  $db = null; // in case of connection failure
758  try {
759  $db = $this->getDB( $serverIndex );
760  for ( $i = 0; $i < $this->shards; $i++ ) {
761  $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
762  }
763  } catch ( DBError $e ) {
764  $this->handleWriteError( $e, $db, $serverIndex );
765  return false;
766  }
767  }
768  return true;
769  }
770 
771  public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
772  // Avoid deadlocks and allow lock reentry if specified
773  if ( isset( $this->locks[$key] ) ) {
774  if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
775  ++$this->locks[$key]['depth'];
776  return true;
777  } else {
778  return false;
779  }
780  }
781 
782  list( $serverIndex ) = $this->getTableByKey( $key );
783 
784  $db = null; // in case of connection failure
785  try {
786  $db = $this->getDB( $serverIndex );
787  $ok = $db->lock( $key, __METHOD__, $timeout );
788  if ( $ok ) {
789  $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
790  }
791 
792  $this->logger->warning(
793  __METHOD__ . " failed due to timeout for {key}.",
794  [ 'key' => $key, 'timeout' => $timeout ]
795  );
796 
797  return $ok;
798  } catch ( DBError $e ) {
799  $this->handleWriteError( $e, $db, $serverIndex );
800  $ok = false;
801  }
802 
803  return $ok;
804  }
805 
806  public function unlock( $key ) {
807  if ( !isset( $this->locks[$key] ) ) {
808  return false;
809  }
810 
811  if ( --$this->locks[$key]['depth'] <= 0 ) {
812  unset( $this->locks[$key] );
813 
814  list( $serverIndex ) = $this->getTableByKey( $key );
815 
816  $db = null; // in case of connection failure
817  try {
818  $db = $this->getDB( $serverIndex );
819  $ok = $db->unlock( $key, __METHOD__ );
820  if ( !$ok ) {
821  $this->logger->warning(
822  __METHOD__ . ' failed to release lock for {key}.',
823  [ 'key' => $key ]
824  );
825  }
826  } catch ( DBError $e ) {
827  $this->handleWriteError( $e, $db, $serverIndex );
828  $ok = false;
829  }
830 
831  return $ok;
832  }
833 
834  return true;
835  }
836 
845  protected function serialize( $data ) {
846  if ( is_int( $data ) ) {
847  return $data;
848  }
849 
850  $serial = serialize( $data );
851  if ( function_exists( 'gzdeflate' ) ) {
852  $serial = gzdeflate( $serial );
853  }
854 
855  return $serial;
856  }
857 
863  protected function unserialize( $serial ) {
864  if ( $this->isInteger( $serial ) ) {
865  return (int)$serial;
866  }
867 
868  if ( function_exists( 'gzinflate' ) ) {
869  Wikimedia\suppressWarnings();
870  $decomp = gzinflate( $serial );
871  Wikimedia\restoreWarnings();
872 
873  if ( $decomp !== false ) {
874  $serial = $decomp;
875  }
876  }
877 
878  return unserialize( $serial );
879  }
880 
887  protected function handleReadError( DBError $exception, $serverIndex ) {
888  if ( $exception instanceof DBConnectionError ) {
889  $this->markServerDown( $exception, $serverIndex );
890  }
891 
892  $this->setAndLogDBError( $exception );
893  }
894 
903  protected function handleWriteError( DBError $exception, $db, $serverIndex ) {
904  if ( !( $db instanceof IDatabase ) ) {
905  $this->markServerDown( $exception, $serverIndex );
906  }
907 
908  $this->setAndLogDBError( $exception );
909  }
910 
914  private function setAndLogDBError( DBError $exception ) {
915  $this->logger->error( "DBError: {$exception->getMessage()}" );
916  if ( $exception instanceof DBConnectionError ) {
918  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
919  } else {
921  $this->logger->debug( __METHOD__ . ": ignoring query error" );
922  }
923  }
924 
931  protected function markServerDown( DBError $exception, $serverIndex ) {
932  unset( $this->conns[$serverIndex] ); // bug T103435
933 
934  if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
935  if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
936  unset( $this->connFailureTimes[$serverIndex] );
937  unset( $this->connFailureErrors[$serverIndex] );
938  } else {
939  $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
940  return;
941  }
942  }
943  $now = time();
944  $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
945  $this->connFailureTimes[$serverIndex] = $now;
946  $this->connFailureErrors[$serverIndex] = $exception;
947  }
948 
952  public function createTables() {
953  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
954  $db = $this->getDB( $serverIndex );
955  if ( $db->getType() !== 'mysql' ) {
956  throw new MWException( __METHOD__ . ' is not supported on this DB server' );
957  }
958 
959  for ( $i = 0; $i < $this->shards; $i++ ) {
960  $db->query(
961  'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
962  ' LIKE ' . $db->tableName( 'objectcache' ),
963  __METHOD__ );
964  }
965  }
966  }
967 
971  protected function usesMainDB() {
972  return !$this->serverInfos;
973  }
974 
975  protected function waitForReplication() {
976  if ( !$this->usesMainDB() ) {
977  // Custom DB server list; probably doesn't use replication
978  return true;
979  }
980 
981  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
982  if ( $lb->getServerCount() <= 1 ) {
983  return true; // no replica DBs
984  }
985 
986  // Main LB is used; wait for any replica DBs to catch up
987  try {
988  $masterPos = $lb->getMasterPos();
989  if ( !$masterPos ) {
990  return true; // not applicable
991  }
992 
993  $loop = new WaitConditionLoop(
994  function () use ( $lb, $masterPos ) {
995  return $lb->waitForAll( $masterPos, 1 );
996  },
999  );
1000 
1001  return ( $loop->invoke() === $loop::CONDITION_REACHED );
1002  } catch ( DBError $e ) {
1003  $this->setAndLogDBError( $e );
1004 
1005  return false;
1006  }
1007  }
1008 
1015  protected function silenceTransactionProfiler() {
1016  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1017  $oldSilenced = $trxProfiler->setSilenced( true );
1018  return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1019  $trxProfiler->setSilenced( $oldSilenced );
1020  } );
1021  }
1022 }
static string $OP_DELETE
modifyMulti(array $data, $exptime, $flags, $op)
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2620
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
unserialize( $serial)
Unserialize and, if necessary, decompress an object.
affectedRows()
Get the number of rows affected by the last write query.
$success
doSet( $key, $value, $exptime=0, $flags=0)
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
handleWriteError(DBError $exception, $db, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
array [] $serverInfos
(server index => server config)
debug( $text)
Definition: BagOStuff.php:947
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2146
static instance()
Singleton.
Definition: Profiler.php:62
static string $OP_SET
deleteServerObjectsExpiringBefore(IDatabase $db, $timestamp, $progressCallback, $limit, $serversDoneCount=0, &$keysDeletedCount=0)
$value
lock( $key, $timeout=6, $expiry=6, $rclass='')
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
Definition: hooks.txt:2138
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
setLastError( $err)
Set the "last error" registry.
Definition: BagOStuff.php:916
int $lastGarbageCollect
UNIX timestamp.
const DB_MASTER
Definition: defines.php:26
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1969
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
convertToExpiry( $exptime)
Convert an optionally relative timestamp to an absolute time.
Definition: BagOStuff.php:973
mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags)
Definition: BagOStuff.php:411
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getMaxDateTime( $db)
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
callable [] $busyCallbacks
Definition: BagOStuff.php:92
string [] $serverTags
(server index => tag/host name)
fetchBlobMulti(array $keys, $flags=0)
string $tableName
$res
Definition: database.txt:21
markServerDown(DBError $exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
$params
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
createTables()
Create shard tables.
doChangeTTL( $key, $exptime, $flags)
occasionallyGarbageCollect(IDatabase $db)
deleteAll()
Delete content of shard tables in every server.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
doGet( $key, $flags=0, &$casToken=null)
const DBO_TRX
Definition: defines.php:12
cas( $casToken, $key, $value, $exptime=0, $flags=0)
doGetMulti(array $keys, $flags=0)
static string $OP_TOUCH
add( $key, $value, $exptime=0, $flags=0)
LoadBalancer null $separateMainLB
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
doSetMulti(array $data, $exptime=0, $flags=0)
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
array $connFailureTimes
UNIX timestamps.
doChangeTTLMulti(array $keys, $exptime, $flags=0)
static consistentHashSort(&$array, $key, $separator="\0")
Sort the given array in a pseudo-random order which depends only on the given key and each element va...
Definition: ArrayUtils.php:49
getTableNameByShard( $index)
Get the table name for a given shard index.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry)
doDelete( $key, $flags=0)
getTableByKey( $key)
Get the server index and table name for a given key.
doDeleteMulti(array $keys, $flags=0)
static int $GARBAGE_COLLECT_DELAY_SEC
const DB_REPLICA
Definition: defines.php:25
Class to store objects in the database.
incr( $key, $step=1)
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
getDB( $serverIndex)
Get a connection to the specified database.
isInteger( $value)
Check if a value is an integer.
Definition: BagOStuff.php:998
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF)
isExpired( $db, $exptime)
silenceTransactionProfiler()
Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is destroy...
addQuotes( $s)
Adds quotes and backslashes.
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Database error base class.
Definition: DBError.php:30
array $connFailureErrors
Exceptions.
callable null $asyncHandler
Definition: BagOStuff.php:74
setAndLogDBError(DBError $exception)
__construct( $params)
Constructor.
serialize( $data)
Serialize an object and, if possible, compress the representation.
static string $OP_ADD