MediaWiki  1.33.0
SqlBagOStuff.php
Go to the documentation of this file.
1 <?php
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\WaitConditionLoop;
33 
39 class SqlBagOStuff extends BagOStuff {
41  protected $serverInfos;
43  protected $serverTags;
45  protected $numServers;
47  protected $lastExpireAll = 0;
49  protected $purgePeriod = 100;
51  protected $shards = 1;
53  protected $tableName = 'objectcache';
55  protected $replicaOnly = false;
57  protected $syncTimeout = 3;
58 
60  protected $separateMainLB;
62  protected $conns;
64  protected $connFailureTimes = [];
66  protected $connFailureErrors = [];
67 
106  public function __construct( $params ) {
107  parent::__construct( $params );
108 
111 
112  if ( isset( $params['servers'] ) ) {
113  $this->serverInfos = [];
114  $this->serverTags = [];
115  $this->numServers = count( $params['servers'] );
116  $index = 0;
117  foreach ( $params['servers'] as $tag => $info ) {
118  $this->serverInfos[$index] = $info;
119  if ( is_string( $tag ) ) {
120  $this->serverTags[$index] = $tag;
121  } else {
122  $this->serverTags[$index] = $info['host'] ?? "#$index";
123  }
124  ++$index;
125  }
126  } elseif ( isset( $params['server'] ) ) {
127  $this->serverInfos = [ $params['server'] ];
128  $this->numServers = count( $this->serverInfos );
129  } else {
130  // Default to using the main wiki's database servers
131  $this->serverInfos = false;
132  $this->numServers = 1;
134  }
135  if ( isset( $params['purgePeriod'] ) ) {
136  $this->purgePeriod = intval( $params['purgePeriod'] );
137  }
138  if ( isset( $params['tableName'] ) ) {
139  $this->tableName = $params['tableName'];
140  }
141  if ( isset( $params['shards'] ) ) {
142  $this->shards = intval( $params['shards'] );
143  }
144  if ( isset( $params['syncTimeout'] ) ) {
145  $this->syncTimeout = $params['syncTimeout'];
146  }
147  $this->replicaOnly = !empty( $params['slaveOnly'] );
148  }
149 
157  protected function getDB( $serverIndex ) {
158  if ( !isset( $this->conns[$serverIndex] ) ) {
159  if ( $serverIndex >= $this->numServers ) {
160  throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
161  }
162 
163  # Don't keep timing out trying to connect for each call if the DB is down
164  if ( isset( $this->connFailureErrors[$serverIndex] )
165  && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
166  ) {
167  throw $this->connFailureErrors[$serverIndex];
168  }
169 
170  if ( $this->serverInfos ) {
171  // Use custom database defined by server connection info
172  $info = $this->serverInfos[$serverIndex];
173  $type = $info['type'] ?? 'mysql';
174  $host = $info['host'] ?? '[unknown]';
175  $this->logger->debug( __CLASS__ . ": connecting to $host" );
176  $db = Database::factory( $type, $info );
177  $db->clearFlag( DBO_TRX ); // auto-commit mode
178  } else {
179  // Use the main LB database
180  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
181  $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
182  if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
183  // Keep a separate connection to avoid contention and deadlocks
184  $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
185  } else {
186  // However, SQLite has the opposite behavior due to DB-level locking.
187  // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
188  $db = $lb->getConnection( $index );
189  }
190  }
191 
192  $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
193  $this->conns[$serverIndex] = $db;
194  }
195 
196  return $this->conns[$serverIndex];
197  }
198 
204  protected function getTableByKey( $key ) {
205  if ( $this->shards > 1 ) {
206  $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
207  $tableIndex = $hash % $this->shards;
208  } else {
209  $tableIndex = 0;
210  }
211  if ( $this->numServers > 1 ) {
212  $sortedServers = $this->serverTags;
213  ArrayUtils::consistentHashSort( $sortedServers, $key );
214  reset( $sortedServers );
215  $serverIndex = key( $sortedServers );
216  } else {
217  $serverIndex = 0;
218  }
219  return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
220  }
221 
227  protected function getTableNameByShard( $index ) {
228  if ( $this->shards > 1 ) {
229  $decimals = strlen( $this->shards - 1 );
230  return $this->tableName .
231  sprintf( "%0{$decimals}d", $index );
232  } else {
233  return $this->tableName;
234  }
235  }
236 
237  protected function doGet( $key, $flags = 0, &$casToken = null ) {
238  $casToken = null;
239 
240  $blobs = $this->fetchBlobMulti( [ $key ] );
241  if ( array_key_exists( $key, $blobs ) ) {
242  $blob = $blobs[$key];
243  $value = $this->unserialize( $blob );
244 
245  $casToken = ( $value !== false ) ? $blob : null;
246 
247  return $value;
248  }
249 
250  return false;
251  }
252 
253  public function getMulti( array $keys, $flags = 0 ) {
254  $values = [];
255 
256  $blobs = $this->fetchBlobMulti( $keys );
257  foreach ( $blobs as $key => $blob ) {
258  $values[$key] = $this->unserialize( $blob );
259  }
260 
261  return $values;
262  }
263 
264  public function fetchBlobMulti( array $keys, $flags = 0 ) {
265  $values = []; // array of (key => value)
266 
267  $keysByTable = [];
268  foreach ( $keys as $key ) {
269  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
270  $keysByTable[$serverIndex][$tableName][] = $key;
271  }
272 
273  $this->garbageCollect(); // expire old entries if any
274 
275  $dataRows = [];
276  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
277  try {
278  $db = $this->getDB( $serverIndex );
279  foreach ( $serverKeys as $tableName => $tableKeys ) {
280  $res = $db->select( $tableName,
281  [ 'keyname', 'value', 'exptime' ],
282  [ 'keyname' => $tableKeys ],
283  __METHOD__,
284  // Approximate write-on-the-fly BagOStuff API via blocking.
285  // This approximation fails if a ROLLBACK happens (which is rare).
286  // We do not want to flush the TRX as that can break callers.
287  $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
288  );
289  if ( $res === false ) {
290  continue;
291  }
292  foreach ( $res as $row ) {
293  $row->serverIndex = $serverIndex;
294  $row->tableName = $tableName;
295  $dataRows[$row->keyname] = $row;
296  }
297  }
298  } catch ( DBError $e ) {
299  $this->handleReadError( $e, $serverIndex );
300  }
301  }
302 
303  foreach ( $keys as $key ) {
304  if ( isset( $dataRows[$key] ) ) { // HIT?
305  $row = $dataRows[$key];
306  $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
307  $db = null;
308  try {
309  $db = $this->getDB( $row->serverIndex );
310  if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
311  $this->debug( "get: key has expired" );
312  } else { // HIT
313  $values[$key] = $db->decodeBlob( $row->value );
314  }
315  } catch ( DBQueryError $e ) {
316  $this->handleWriteError( $e, $db, $row->serverIndex );
317  }
318  } else { // MISS
319  $this->debug( 'get: no matching rows' );
320  }
321  }
322 
323  return $values;
324  }
325 
326  public function setMulti( array $data, $expiry = 0, $flags = 0 ) {
327  return $this->insertMulti( $data, $expiry, $flags, true );
328  }
329 
330  private function insertMulti( array $data, $expiry, $flags, $replace ) {
331  $keysByTable = [];
332  foreach ( $data as $key => $value ) {
333  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
334  $keysByTable[$serverIndex][$tableName][] = $key;
335  }
336 
337  $this->garbageCollect(); // expire old entries if any
338 
339  $result = true;
340  $exptime = (int)$expiry;
341  $silenceScope = $this->silenceTransactionProfiler();
342  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
343  $db = null;
344  try {
345  $db = $this->getDB( $serverIndex );
346  } catch ( DBError $e ) {
347  $this->handleWriteError( $e, $db, $serverIndex );
348  $result = false;
349  continue;
350  }
351 
352  if ( $exptime < 0 ) {
353  $exptime = 0;
354  }
355 
356  if ( $exptime == 0 ) {
357  $encExpiry = $this->getMaxDateTime( $db );
358  } else {
359  $exptime = $this->convertToExpiry( $exptime );
360  $encExpiry = $db->timestamp( $exptime );
361  }
362  foreach ( $serverKeys as $tableName => $tableKeys ) {
363  $rows = [];
364  foreach ( $tableKeys as $key ) {
365  $rows[] = [
366  'keyname' => $key,
367  'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
368  'exptime' => $encExpiry,
369  ];
370  }
371 
372  try {
373  if ( $replace ) {
374  $db->replace( $tableName, [ 'keyname' ], $rows, __METHOD__ );
375  } else {
376  $db->insert( $tableName, $rows, __METHOD__, [ 'IGNORE' ] );
377  $result = ( $db->affectedRows() > 0 && $result );
378  }
379  } catch ( DBError $e ) {
380  $this->handleWriteError( $e, $db, $serverIndex );
381  $result = false;
382  }
383 
384  }
385  }
386 
387  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
388  $result = $this->waitForReplication() && $result;
389  }
390 
391  return $result;
392  }
393 
394  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
395  $ok = $this->setMulti( [ $key => $value ], $exptime );
396 
397  return $ok;
398  }
399 
400  public function add( $key, $value, $exptime = 0, $flags = 0 ) {
401  $added = $this->insertMulti( [ $key => $value ], $exptime, $flags, false );
402 
403  return $added;
404  }
405 
406  protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
407  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
408  $db = null;
409  $silenceScope = $this->silenceTransactionProfiler();
410  try {
411  $db = $this->getDB( $serverIndex );
412  $exptime = intval( $exptime );
413 
414  if ( $exptime < 0 ) {
415  $exptime = 0;
416  }
417 
418  if ( $exptime == 0 ) {
419  $encExpiry = $this->getMaxDateTime( $db );
420  } else {
421  $exptime = $this->convertToExpiry( $exptime );
422  $encExpiry = $db->timestamp( $exptime );
423  }
424  // (T26425) use a replace if the db supports it instead of
425  // delete/insert to avoid clashes with conflicting keynames
426  $db->update(
427  $tableName,
428  [
429  'keyname' => $key,
430  'value' => $db->encodeBlob( $this->serialize( $value ) ),
431  'exptime' => $encExpiry
432  ],
433  [
434  'keyname' => $key,
435  'value' => $db->encodeBlob( $casToken )
436  ],
437  __METHOD__
438  );
439  } catch ( DBQueryError $e ) {
440  $this->handleWriteError( $e, $db, $serverIndex );
441 
442  return false;
443  }
444 
445  return (bool)$db->affectedRows();
446  }
447 
448  public function deleteMulti( array $keys, $flags = 0 ) {
449  $keysByTable = [];
450  foreach ( $keys as $key ) {
451  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
452  $keysByTable[$serverIndex][$tableName][] = $key;
453  }
454 
455  $result = true;
456  $silenceScope = $this->silenceTransactionProfiler();
457  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
458  $db = null;
459  try {
460  $db = $this->getDB( $serverIndex );
461  } catch ( DBError $e ) {
462  $this->handleWriteError( $e, $db, $serverIndex );
463  $result = false;
464  continue;
465  }
466 
467  foreach ( $serverKeys as $tableName => $tableKeys ) {
468  try {
469  $db->delete( $tableName, [ 'keyname' => $tableKeys ], __METHOD__ );
470  } catch ( DBError $e ) {
471  $this->handleWriteError( $e, $db, $serverIndex );
472  $result = false;
473  }
474 
475  }
476  }
477 
478  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
479  $result = $this->waitForReplication() && $result;
480  }
481 
482  return $result;
483  }
484 
485  public function delete( $key, $flags = 0 ) {
486  $ok = $this->deleteMulti( [ $key ], $flags );
487 
488  return $ok;
489  }
490 
491  public function incr( $key, $step = 1 ) {
492  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
493  $db = null;
494  $silenceScope = $this->silenceTransactionProfiler();
495  try {
496  $db = $this->getDB( $serverIndex );
497  $step = intval( $step );
498  $row = $db->selectRow(
499  $tableName,
500  [ 'value', 'exptime' ],
501  [ 'keyname' => $key ],
502  __METHOD__,
503  [ 'FOR UPDATE' ]
504  );
505  if ( $row === false ) {
506  // Missing
507  return false;
508  }
509  $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
510  if ( $this->isExpired( $db, $row->exptime ) ) {
511  // Expired, do not reinsert
512  return false;
513  }
514 
515  $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
516  $newValue = $oldValue + $step;
517  $db->insert(
518  $tableName,
519  [
520  'keyname' => $key,
521  'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
522  'exptime' => $row->exptime
523  ],
524  __METHOD__,
525  'IGNORE'
526  );
527 
528  if ( $db->affectedRows() == 0 ) {
529  // Race condition. See T30611
530  $newValue = false;
531  }
532  } catch ( DBError $e ) {
533  $this->handleWriteError( $e, $db, $serverIndex );
534  return false;
535  }
536 
537  return $newValue;
538  }
539 
540  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
541  $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
542  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
543  $ok = $this->waitForReplication() && $ok;
544  }
545 
546  return $ok;
547  }
548 
549  public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
550  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
551  $db = null;
552  $silenceScope = $this->silenceTransactionProfiler();
553  try {
554  $db = $this->getDB( $serverIndex );
555  if ( $exptime == 0 ) {
556  $timestamp = $this->getMaxDateTime( $db );
557  } else {
558  $timestamp = $db->timestamp( $this->convertToExpiry( $exptime ) );
559  }
560  $db->update(
561  $tableName,
562  [ 'exptime' => $timestamp ],
563  [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
564  __METHOD__
565  );
566  if ( $db->affectedRows() == 0 ) {
567  $exists = (bool)$db->selectField(
568  $tableName,
569  1,
570  [ 'keyname' => $key, 'exptime' => $timestamp ],
571  __METHOD__,
572  [ 'FOR UPDATE' ]
573  );
574 
575  return $exists;
576  }
577  } catch ( DBError $e ) {
578  $this->handleWriteError( $e, $db, $serverIndex );
579  return false;
580  }
581 
582  return true;
583  }
584 
590  protected function isExpired( $db, $exptime ) {
591  return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
592  }
593 
598  protected function getMaxDateTime( $db ) {
599  if ( time() > 0x7fffffff ) {
600  return $db->timestamp( 1 << 62 );
601  } else {
602  return $db->timestamp( 0x7fffffff );
603  }
604  }
605 
606  protected function garbageCollect() {
607  if ( !$this->purgePeriod || $this->replicaOnly ) {
608  // Disabled
609  return;
610  }
611  // Only purge on one in every $this->purgePeriod requests.
612  if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
613  return;
614  }
615  $now = time();
616  // Avoid repeating the delete within a few seconds
617  if ( $now > ( $this->lastExpireAll + 1 ) ) {
618  $this->lastExpireAll = $now;
619  $this->expireAll();
620  }
621  }
622 
623  public function expireAll() {
625  }
626 
633  public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
634  $silenceScope = $this->silenceTransactionProfiler();
635  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
636  $db = null;
637  try {
638  $db = $this->getDB( $serverIndex );
639  $dbTimestamp = $db->timestamp( $timestamp );
640  $totalSeconds = false;
641  $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
642  for ( $i = 0; $i < $this->shards; $i++ ) {
643  $maxExpTime = false;
644  while ( true ) {
645  $conds = $baseConds;
646  if ( $maxExpTime !== false ) {
647  $conds[] = 'exptime >= ' . $db->addQuotes( $maxExpTime );
648  }
649  $rows = $db->select(
650  $this->getTableNameByShard( $i ),
651  [ 'keyname', 'exptime' ],
652  $conds,
653  __METHOD__,
654  [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
655  if ( $rows === false || !$rows->numRows() ) {
656  break;
657  }
658  $keys = [];
659  $row = $rows->current();
660  $minExpTime = $row->exptime;
661  if ( $totalSeconds === false ) {
662  $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
663  - wfTimestamp( TS_UNIX, $minExpTime );
664  }
665  foreach ( $rows as $row ) {
666  $keys[] = $row->keyname;
667  $maxExpTime = $row->exptime;
668  }
669 
670  $db->delete(
671  $this->getTableNameByShard( $i ),
672  [
673  'exptime >= ' . $db->addQuotes( $minExpTime ),
674  'exptime < ' . $db->addQuotes( $dbTimestamp ),
675  'keyname' => $keys
676  ],
677  __METHOD__ );
678 
679  if ( $progressCallback ) {
680  if ( intval( $totalSeconds ) === 0 ) {
681  $percent = 0;
682  } else {
683  $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
684  - wfTimestamp( TS_UNIX, $maxExpTime );
685  if ( $remainingSeconds > $totalSeconds ) {
686  $totalSeconds = $remainingSeconds;
687  }
688  $processedSeconds = $totalSeconds - $remainingSeconds;
689  $percent = ( $i + $processedSeconds / $totalSeconds )
690  / $this->shards * 100;
691  }
692  $percent = ( $percent / $this->numServers )
693  + ( $serverIndex / $this->numServers * 100 );
694  call_user_func( $progressCallback, $percent );
695  }
696  }
697  }
698  } catch ( DBError $e ) {
699  $this->handleWriteError( $e, $db, $serverIndex );
700  return false;
701  }
702  }
703  return true;
704  }
705 
711  public function deleteAll() {
712  $silenceScope = $this->silenceTransactionProfiler();
713  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
714  $db = null;
715  try {
716  $db = $this->getDB( $serverIndex );
717  for ( $i = 0; $i < $this->shards; $i++ ) {
718  $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
719  }
720  } catch ( DBError $e ) {
721  $this->handleWriteError( $e, $db, $serverIndex );
722  return false;
723  }
724  }
725  return true;
726  }
727 
736  protected function serialize( &$data ) {
737  $serial = serialize( $data );
738 
739  if ( function_exists( 'gzdeflate' ) ) {
740  return gzdeflate( $serial );
741  } else {
742  return $serial;
743  }
744  }
745 
751  protected function unserialize( $serial ) {
752  if ( function_exists( 'gzinflate' ) ) {
753  Wikimedia\suppressWarnings();
754  $decomp = gzinflate( $serial );
755  Wikimedia\restoreWarnings();
756 
757  if ( $decomp !== false ) {
758  $serial = $decomp;
759  }
760  }
761 
762  $ret = unserialize( $serial );
763 
764  return $ret;
765  }
766 
773  protected function handleReadError( DBError $exception, $serverIndex ) {
774  if ( $exception instanceof DBConnectionError ) {
775  $this->markServerDown( $exception, $serverIndex );
776  }
777 
778  $this->setAndLogDBError( $exception );
779  }
780 
789  protected function handleWriteError( DBError $exception, IDatabase $db = null, $serverIndex ) {
790  if ( !$db ) {
791  $this->markServerDown( $exception, $serverIndex );
792  }
793 
794  $this->setAndLogDBError( $exception );
795  }
796 
800  private function setAndLogDBError( DBError $exception ) {
801  $this->logger->error( "DBError: {$exception->getMessage()}" );
802  if ( $exception instanceof DBConnectionError ) {
804  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
805  } else {
807  $this->logger->debug( __METHOD__ . ": ignoring query error" );
808  }
809  }
810 
817  protected function markServerDown( DBError $exception, $serverIndex ) {
818  unset( $this->conns[$serverIndex] ); // bug T103435
819 
820  if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
821  if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
822  unset( $this->connFailureTimes[$serverIndex] );
823  unset( $this->connFailureErrors[$serverIndex] );
824  } else {
825  $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
826  return;
827  }
828  }
829  $now = time();
830  $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
831  $this->connFailureTimes[$serverIndex] = $now;
832  $this->connFailureErrors[$serverIndex] = $exception;
833  }
834 
838  public function createTables() {
839  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
840  $db = $this->getDB( $serverIndex );
841  if ( $db->getType() !== 'mysql' ) {
842  throw new MWException( __METHOD__ . ' is not supported on this DB server' );
843  }
844 
845  for ( $i = 0; $i < $this->shards; $i++ ) {
846  $db->query(
847  'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
848  ' LIKE ' . $db->tableName( 'objectcache' ),
849  __METHOD__ );
850  }
851  }
852  }
853 
857  protected function usesMainDB() {
858  return !$this->serverInfos;
859  }
860 
861  protected function waitForReplication() {
862  if ( !$this->usesMainDB() ) {
863  // Custom DB server list; probably doesn't use replication
864  return true;
865  }
866 
867  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
868  if ( $lb->getServerCount() <= 1 ) {
869  return true; // no replica DBs
870  }
871 
872  // Main LB is used; wait for any replica DBs to catch up
873  try {
874  $masterPos = $lb->getMasterPos();
875  if ( !$masterPos ) {
876  return true; // not applicable
877  }
878 
879  $loop = new WaitConditionLoop(
880  function () use ( $lb, $masterPos ) {
881  return $lb->waitForAll( $masterPos, 1 );
882  },
885  );
886 
887  return ( $loop->invoke() === $loop::CONDITION_REACHED );
888  } catch ( DBError $e ) {
889  $this->setAndLogDBError( $e );
890 
891  return false;
892  }
893  }
894 
901  protected function silenceTransactionProfiler() {
902  $trxProfiler = Profiler::instance()->getTransactionProfiler();
903  $oldSilenced = $trxProfiler->setSilenced( true );
904  return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
905  $trxProfiler->setSilenced( $oldSilenced );
906  } );
907  }
908 }
SqlBagOStuff\__construct
__construct( $params)
Constructor.
Definition: SqlBagOStuff.php:106
SqlBagOStuff\createTables
createTables()
Create shard tables.
Definition: SqlBagOStuff.php:838
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
ArrayUtils\consistentHashSort
static consistentHashSort(&$array, $key, $separator="\000")
Sort the given array in a pseudo-random order which depends only on the given key and each element va...
Definition: ArrayUtils.php:49
SqlBagOStuff\doGet
doGet( $key, $flags=0, &$casToken=null)
Definition: SqlBagOStuff.php:237
SqlBagOStuff\merge
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
Definition: SqlBagOStuff.php:540
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
SqlBagOStuff\cas
cas( $casToken, $key, $value, $exptime=0, $flags=0)
Check and set an item.
Definition: SqlBagOStuff.php:406
IExpiringStore\ERR_UNEXPECTED
const ERR_UNEXPECTED
Definition: IExpiringStore.php:66
SqlBagOStuff\$lastExpireAll
int $lastExpireAll
Definition: SqlBagOStuff.php:47
SqlBagOStuff\setAndLogDBError
setAndLogDBError(DBError $exception)
Definition: SqlBagOStuff.php:800
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:62
SqlBagOStuff\serialize
serialize(&$data)
Serialize an object and, if possible, compress the representation.
Definition: SqlBagOStuff.php:736
SqlBagOStuff\$separateMainLB
LoadBalancer null $separateMainLB
Definition: SqlBagOStuff.php:60
captcha-old.count
count
Definition: captcha-old.py:249
SqlBagOStuff\$serverInfos
array[] $serverInfos
(server index => server config)
Definition: SqlBagOStuff.php:41
SqlBagOStuff\$conns
array $conns
Definition: SqlBagOStuff.php:62
IExpiringStore\QOS_EMULATION_SQL
const QOS_EMULATION_SQL
Definition: IExpiringStore.php:50
$result
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. '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:1983
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1912
SqlBagOStuff\incr
incr( $key, $step=1)
Increase stored value of $key by $value while preserving its TTL.
Definition: SqlBagOStuff.php:491
BagOStuff\debug
debug( $text)
Definition: BagOStuff.php:680
SqlBagOStuff\silenceTransactionProfiler
silenceTransactionProfiler()
Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is destroy...
Definition: SqlBagOStuff.php:901
BagOStuff\mergeViaCas
mergeViaCas( $key, $callback, $exptime=0, $attempts=10, $flags=0)
Definition: BagOStuff.php:289
$params
$params
Definition: styleTest.css.php:44
IExpiringStore\ERR_UNREACHABLE
const ERR_UNREACHABLE
Definition: IExpiringStore.php:65
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
$res
$res
Definition: database.txt:21
SqlBagOStuff\deleteMulti
deleteMulti(array $keys, $flags=0)
Batch deletion.
Definition: SqlBagOStuff.php:448
SqlBagOStuff\handleWriteError
handleWriteError(DBError $exception, IDatabase $db=null, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
Definition: SqlBagOStuff.php:789
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
DBO_TRX
const DBO_TRX
Definition: defines.php:12
php
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
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
IExpiringStore\ATTR_EMULATION
const ATTR_EMULATION
Definition: IExpiringStore.php:48
SqlBagOStuff\getTableByKey
getTableByKey( $key)
Get the server index and table name for a given key.
Definition: SqlBagOStuff.php:204
SqlBagOStuff\$syncTimeout
int $syncTimeout
Definition: SqlBagOStuff.php:57
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
SqlBagOStuff\expireAll
expireAll()
Definition: SqlBagOStuff.php:623
MWException
MediaWiki exception.
Definition: MWException.php:26
SqlBagOStuff\deleteAll
deleteAll()
Delete content of shard tables in every server.
Definition: SqlBagOStuff.php:711
SqlBagOStuff\getDB
getDB( $serverIndex)
Get a connection to the specified database.
Definition: SqlBagOStuff.php:157
$blob
$blob
Definition: testCompression.php:65
tableName
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
SqlBagOStuff\$connFailureErrors
array $connFailureErrors
Exceptions.
Definition: SqlBagOStuff.php:66
SqlBagOStuff\getMulti
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
Definition: SqlBagOStuff.php:253
SqlBagOStuff\fetchBlobMulti
fetchBlobMulti(array $keys, $flags=0)
Definition: SqlBagOStuff.php:264
SqlBagOStuff\handleReadError
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
Definition: SqlBagOStuff.php:773
IExpiringStore\QOS_SYNCWRITES_BE
const QOS_SYNCWRITES_BE
Definition: IExpiringStore.php:56
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
SqlBagOStuff\isExpired
isExpired( $db, $exptime)
Definition: SqlBagOStuff.php:590
SqlBagOStuff\$tableName
string $tableName
Definition: SqlBagOStuff.php:53
BagOStuff\$busyCallbacks
callable[] $busyCallbacks
Definition: BagOStuff.php:82
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1941
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
list
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
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:41
SqlBagOStuff\waitForReplication
waitForReplication()
Definition: SqlBagOStuff.php:861
SqlBagOStuff\insertMulti
insertMulti(array $data, $expiry, $flags, $replace)
Definition: SqlBagOStuff.php:330
key
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:2154
SqlBagOStuff\add
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
Definition: SqlBagOStuff.php:400
SqlBagOStuff\changeTTL
changeTTL( $key, $exptime=0, $flags=0)
Change the expiration on a key if it exists.
Definition: SqlBagOStuff.php:549
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
SqlBagOStuff\garbageCollect
garbageCollect()
Definition: SqlBagOStuff.php:606
$value
$value
Definition: styleTest.css.php:49
SqlBagOStuff\unserialize
unserialize( $serial)
Unserialize and, if necessary, decompress an object.
Definition: SqlBagOStuff.php:751
SqlBagOStuff\deleteObjectsExpiringBefore
deleteObjectsExpiringBefore( $timestamp, $progressCallback=false)
Delete objects from the database which expire before a certain date.
Definition: SqlBagOStuff.php:633
SqlBagOStuff\$connFailureTimes
array $connFailureTimes
UNIX timestamps.
Definition: SqlBagOStuff.php:64
IExpiringStore\ATTR_SYNCWRITES
const ATTR_SYNCWRITES
Definition: IExpiringStore.php:53
BagOStuff\convertToExpiry
convertToExpiry( $exptime)
Convert an optionally relative time to an absolute time.
Definition: BagOStuff.php:701
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1985
SqlBagOStuff\$numServers
int $numServers
Definition: SqlBagOStuff.php:45
SqlBagOStuff
Class to store objects in the database.
Definition: SqlBagOStuff.php:39
$rows
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:2636
as
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
SqlBagOStuff\getMaxDateTime
getMaxDateTime( $db)
Definition: SqlBagOStuff.php:598
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
$keys
$keys
Definition: testCompression.php:67
SqlBagOStuff\$serverTags
string[] $serverTags
(server index => tag/host name)
Definition: SqlBagOStuff.php:43
MediaWikiServices
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
SqlBagOStuff\$replicaOnly
bool $replicaOnly
Definition: SqlBagOStuff.php:55
SqlBagOStuff\setMulti
setMulti(array $data, $expiry=0, $flags=0)
Batch insertion/replace.
Definition: SqlBagOStuff.php:326
IExpiringStore\QOS_SYNCWRITES_NONE
const QOS_SYNCWRITES_NONE
Definition: IExpiringStore.php:55
SqlBagOStuff\markServerDown
markServerDown(DBError $exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
Definition: SqlBagOStuff.php:817
BagOStuff\setLastError
setLastError( $err)
Set the "last error" registry.
Definition: BagOStuff.php:649
SqlBagOStuff\$purgePeriod
int $purgePeriod
Definition: SqlBagOStuff.php:49
SqlBagOStuff\usesMainDB
usesMainDB()
Definition: SqlBagOStuff.php:857
SqlBagOStuff\$shards
int $shards
Definition: SqlBagOStuff.php:51
SqlBagOStuff\getTableNameByShard
getTableNameByShard( $index)
Get the table name for a given shard index.
Definition: SqlBagOStuff.php:227
$type
$type
Definition: testCompression.php:48