MediaWiki  1.29.1
SqlBagOStuff.php
Go to the documentation of this file.
1 <?php
30 use \Wikimedia\WaitConditionLoop;
31 use \Wikimedia\Rdbms\TransactionProfiler;
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 
104  public function __construct( $params ) {
105  parent::__construct( $params );
106 
109 
110  if ( isset( $params['servers'] ) ) {
111  $this->serverInfos = [];
112  $this->serverTags = [];
113  $this->numServers = count( $params['servers'] );
114  $index = 0;
115  foreach ( $params['servers'] as $tag => $info ) {
116  $this->serverInfos[$index] = $info;
117  if ( is_string( $tag ) ) {
118  $this->serverTags[$index] = $tag;
119  } else {
120  $this->serverTags[$index] = isset( $info['host'] ) ? $info['host'] : "#$index";
121  }
122  ++$index;
123  }
124  } elseif ( isset( $params['server'] ) ) {
125  $this->serverInfos = [ $params['server'] ];
126  $this->numServers = count( $this->serverInfos );
127  } else {
128  // Default to using the main wiki's database servers
129  $this->serverInfos = false;
130  $this->numServers = 1;
132  }
133  if ( isset( $params['purgePeriod'] ) ) {
134  $this->purgePeriod = intval( $params['purgePeriod'] );
135  }
136  if ( isset( $params['tableName'] ) ) {
137  $this->tableName = $params['tableName'];
138  }
139  if ( isset( $params['shards'] ) ) {
140  $this->shards = intval( $params['shards'] );
141  }
142  if ( isset( $params['syncTimeout'] ) ) {
143  $this->syncTimeout = $params['syncTimeout'];
144  }
145  $this->replicaOnly = !empty( $params['slaveOnly'] );
146  }
147 
148  protected function getSeparateMainLB() {
150 
151  if ( $this->usesMainDB() && $wgDBtype !== 'sqlite' ) {
152  if ( !$this->separateMainLB ) {
153  // We must keep a separate connection to MySQL in order to avoid deadlocks
154  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
155  $this->separateMainLB = $lbFactory->newMainLB();
156  }
157  return $this->separateMainLB;
158  } else {
159  // However, SQLite has an opposite behavior due to DB-level locking
160  return null;
161  }
162  }
163 
171  protected function getDB( $serverIndex ) {
172  if ( !isset( $this->conns[$serverIndex] ) ) {
173  if ( $serverIndex >= $this->numServers ) {
174  throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
175  }
176 
177  # Don't keep timing out trying to connect for each call if the DB is down
178  if ( isset( $this->connFailureErrors[$serverIndex] )
179  && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
180  ) {
181  throw $this->connFailureErrors[$serverIndex];
182  }
183 
184  # If server connection info was given, use that
185  if ( $this->serverInfos ) {
186  $info = $this->serverInfos[$serverIndex];
187  $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
188  $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
189  $this->logger->debug( __CLASS__ . ": connecting to $host" );
190  // Use a blank trx profiler to ignore expections as this is a cache
191  $info['trxProfiler'] = new TransactionProfiler();
192  $db = Database::factory( $type, $info );
193  $db->clearFlag( DBO_TRX );
194  } else {
195  $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
196  if ( $this->getSeparateMainLB() ) {
197  $db = $this->getSeparateMainLB()->getConnection( $index );
198  $db->clearFlag( DBO_TRX ); // auto-commit mode
199  } else {
200  $db = wfGetDB( $index );
201  // Can't mess with transaction rounds (DBO_TRX) :(
202  }
203  }
204  $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
205  $this->conns[$serverIndex] = $db;
206  }
207 
208  return $this->conns[$serverIndex];
209  }
210 
216  protected function getTableByKey( $key ) {
217  if ( $this->shards > 1 ) {
218  $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
219  $tableIndex = $hash % $this->shards;
220  } else {
221  $tableIndex = 0;
222  }
223  if ( $this->numServers > 1 ) {
224  $sortedServers = $this->serverTags;
225  ArrayUtils::consistentHashSort( $sortedServers, $key );
226  reset( $sortedServers );
227  $serverIndex = key( $sortedServers );
228  } else {
229  $serverIndex = 0;
230  }
231  return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
232  }
233 
239  protected function getTableNameByShard( $index ) {
240  if ( $this->shards > 1 ) {
241  $decimals = strlen( $this->shards - 1 );
242  return $this->tableName .
243  sprintf( "%0{$decimals}d", $index );
244  } else {
245  return $this->tableName;
246  }
247  }
248 
249  protected function doGet( $key, $flags = 0 ) {
250  $casToken = null;
251 
252  return $this->getWithToken( $key, $casToken, $flags );
253  }
254 
255  protected function getWithToken( $key, &$casToken, $flags = 0 ) {
256  $values = $this->getMulti( [ $key ] );
257  if ( array_key_exists( $key, $values ) ) {
258  $casToken = $values[$key];
259  return $values[$key];
260  }
261  return false;
262  }
263 
264  public function getMulti( 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] = $this->unserialize( $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 ) {
327  $keysByTable = [];
328  foreach ( $data as $key => $value ) {
329  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
330  $keysByTable[$serverIndex][$tableName][] = $key;
331  }
332 
333  $this->garbageCollect(); // expire old entries if any
334 
335  $result = true;
336  $exptime = (int)$expiry;
337  foreach ( $keysByTable as $serverIndex => $serverKeys ) {
338  $db = null;
339  try {
340  $db = $this->getDB( $serverIndex );
341  } catch ( DBError $e ) {
342  $this->handleWriteError( $e, $db, $serverIndex );
343  $result = false;
344  continue;
345  }
346 
347  if ( $exptime < 0 ) {
348  $exptime = 0;
349  }
350 
351  if ( $exptime == 0 ) {
352  $encExpiry = $this->getMaxDateTime( $db );
353  } else {
354  $exptime = $this->convertExpiry( $exptime );
355  $encExpiry = $db->timestamp( $exptime );
356  }
357  foreach ( $serverKeys as $tableName => $tableKeys ) {
358  $rows = [];
359  foreach ( $tableKeys as $key ) {
360  $rows[] = [
361  'keyname' => $key,
362  'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
363  'exptime' => $encExpiry,
364  ];
365  }
366 
367  try {
368  $db->replace(
369  $tableName,
370  [ 'keyname' ],
371  $rows,
372  __METHOD__
373  );
374  } catch ( DBError $e ) {
375  $this->handleWriteError( $e, $db, $serverIndex );
376  $result = false;
377  }
378 
379  }
380 
381  }
382 
383  return $result;
384  }
385 
386  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
387  $ok = $this->setMulti( [ $key => $value ], $exptime );
388  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
389  $ok = $this->waitForReplication() && $ok;
390  }
391 
392  return $ok;
393  }
394 
395  protected function cas( $casToken, $key, $value, $exptime = 0 ) {
396  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
397  $db = null;
398  try {
399  $db = $this->getDB( $serverIndex );
400  $exptime = intval( $exptime );
401 
402  if ( $exptime < 0 ) {
403  $exptime = 0;
404  }
405 
406  if ( $exptime == 0 ) {
407  $encExpiry = $this->getMaxDateTime( $db );
408  } else {
409  $exptime = $this->convertExpiry( $exptime );
410  $encExpiry = $db->timestamp( $exptime );
411  }
412  // (T26425) use a replace if the db supports it instead of
413  // delete/insert to avoid clashes with conflicting keynames
414  $db->update(
415  $tableName,
416  [
417  'keyname' => $key,
418  'value' => $db->encodeBlob( $this->serialize( $value ) ),
419  'exptime' => $encExpiry
420  ],
421  [
422  'keyname' => $key,
423  'value' => $db->encodeBlob( $this->serialize( $casToken ) )
424  ],
425  __METHOD__
426  );
427  } catch ( DBQueryError $e ) {
428  $this->handleWriteError( $e, $db, $serverIndex );
429 
430  return false;
431  }
432 
433  return (bool)$db->affectedRows();
434  }
435 
436  public function delete( $key ) {
437  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
438  $db = null;
439  try {
440  $db = $this->getDB( $serverIndex );
441  $db->delete(
442  $tableName,
443  [ 'keyname' => $key ],
444  __METHOD__ );
445  } catch ( DBError $e ) {
446  $this->handleWriteError( $e, $db, $serverIndex );
447  return false;
448  }
449 
450  return true;
451  }
452 
453  public function incr( $key, $step = 1 ) {
454  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
455  $db = null;
456  try {
457  $db = $this->getDB( $serverIndex );
458  $step = intval( $step );
459  $row = $db->selectRow(
460  $tableName,
461  [ 'value', 'exptime' ],
462  [ 'keyname' => $key ],
463  __METHOD__,
464  [ 'FOR UPDATE' ] );
465  if ( $row === false ) {
466  // Missing
467 
468  return null;
469  }
470  $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
471  if ( $this->isExpired( $db, $row->exptime ) ) {
472  // Expired, do not reinsert
473 
474  return null;
475  }
476 
477  $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
478  $newValue = $oldValue + $step;
479  $db->insert( $tableName,
480  [
481  'keyname' => $key,
482  'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
483  'exptime' => $row->exptime
484  ], __METHOD__, 'IGNORE' );
485 
486  if ( $db->affectedRows() == 0 ) {
487  // Race condition. See T30611
488  $newValue = null;
489  }
490  } catch ( DBError $e ) {
491  $this->handleWriteError( $e, $db, $serverIndex );
492  return null;
493  }
494 
495  return $newValue;
496  }
497 
498  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
499  $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
500  if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
501  $ok = $this->waitForReplication() && $ok;
502  }
503 
504  return $ok;
505  }
506 
507  public function changeTTL( $key, $expiry = 0 ) {
508  list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
509  $db = null;
510  try {
511  $db = $this->getDB( $serverIndex );
512  $db->update(
513  $tableName,
514  [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
515  [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
516  __METHOD__
517  );
518  if ( $db->affectedRows() == 0 ) {
519  return false;
520  }
521  } catch ( DBError $e ) {
522  $this->handleWriteError( $e, $db, $serverIndex );
523  return false;
524  }
525 
526  return true;
527  }
528 
534  protected function isExpired( $db, $exptime ) {
535  return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
536  }
537 
542  protected function getMaxDateTime( $db ) {
543  if ( time() > 0x7fffffff ) {
544  return $db->timestamp( 1 << 62 );
545  } else {
546  return $db->timestamp( 0x7fffffff );
547  }
548  }
549 
550  protected function garbageCollect() {
551  if ( !$this->purgePeriod || $this->replicaOnly ) {
552  // Disabled
553  return;
554  }
555  // Only purge on one in every $this->purgePeriod requests.
556  if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
557  return;
558  }
559  $now = time();
560  // Avoid repeating the delete within a few seconds
561  if ( $now > ( $this->lastExpireAll + 1 ) ) {
562  $this->lastExpireAll = $now;
563  $this->expireAll();
564  }
565  }
566 
567  public function expireAll() {
569  }
570 
577  public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
578  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
579  $db = null;
580  try {
581  $db = $this->getDB( $serverIndex );
582  $dbTimestamp = $db->timestamp( $timestamp );
583  $totalSeconds = false;
584  $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
585  for ( $i = 0; $i < $this->shards; $i++ ) {
586  $maxExpTime = false;
587  while ( true ) {
588  $conds = $baseConds;
589  if ( $maxExpTime !== false ) {
590  $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
591  }
592  $rows = $db->select(
593  $this->getTableNameByShard( $i ),
594  [ 'keyname', 'exptime' ],
595  $conds,
596  __METHOD__,
597  [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
598  if ( $rows === false || !$rows->numRows() ) {
599  break;
600  }
601  $keys = [];
602  $row = $rows->current();
603  $minExpTime = $row->exptime;
604  if ( $totalSeconds === false ) {
605  $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
606  - wfTimestamp( TS_UNIX, $minExpTime );
607  }
608  foreach ( $rows as $row ) {
609  $keys[] = $row->keyname;
610  $maxExpTime = $row->exptime;
611  }
612 
613  $db->delete(
614  $this->getTableNameByShard( $i ),
615  [
616  'exptime >= ' . $db->addQuotes( $minExpTime ),
617  'exptime < ' . $db->addQuotes( $dbTimestamp ),
618  'keyname' => $keys
619  ],
620  __METHOD__ );
621 
622  if ( $progressCallback ) {
623  if ( intval( $totalSeconds ) === 0 ) {
624  $percent = 0;
625  } else {
626  $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
627  - wfTimestamp( TS_UNIX, $maxExpTime );
628  if ( $remainingSeconds > $totalSeconds ) {
629  $totalSeconds = $remainingSeconds;
630  }
631  $processedSeconds = $totalSeconds - $remainingSeconds;
632  $percent = ( $i + $processedSeconds / $totalSeconds )
633  / $this->shards * 100;
634  }
635  $percent = ( $percent / $this->numServers )
636  + ( $serverIndex / $this->numServers * 100 );
637  call_user_func( $progressCallback, $percent );
638  }
639  }
640  }
641  } catch ( DBError $e ) {
642  $this->handleWriteError( $e, $db, $serverIndex );
643  return false;
644  }
645  }
646  return true;
647  }
648 
654  public function deleteAll() {
655  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
656  $db = null;
657  try {
658  $db = $this->getDB( $serverIndex );
659  for ( $i = 0; $i < $this->shards; $i++ ) {
660  $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
661  }
662  } catch ( DBError $e ) {
663  $this->handleWriteError( $e, $db, $serverIndex );
664  return false;
665  }
666  }
667  return true;
668  }
669 
678  protected function serialize( &$data ) {
679  $serial = serialize( $data );
680 
681  if ( function_exists( 'gzdeflate' ) ) {
682  return gzdeflate( $serial );
683  } else {
684  return $serial;
685  }
686  }
687 
693  protected function unserialize( $serial ) {
694  if ( function_exists( 'gzinflate' ) ) {
695  MediaWiki\suppressWarnings();
696  $decomp = gzinflate( $serial );
697  MediaWiki\restoreWarnings();
698 
699  if ( false !== $decomp ) {
700  $serial = $decomp;
701  }
702  }
703 
704  $ret = unserialize( $serial );
705 
706  return $ret;
707  }
708 
715  protected function handleReadError( DBError $exception, $serverIndex ) {
716  if ( $exception instanceof DBConnectionError ) {
717  $this->markServerDown( $exception, $serverIndex );
718  }
719  $this->logger->error( "DBError: {$exception->getMessage()}" );
720  if ( $exception instanceof DBConnectionError ) {
722  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
723  } else {
725  $this->logger->debug( __METHOD__ . ": ignoring query error" );
726  }
727  }
728 
737  protected function handleWriteError( DBError $exception, IDatabase $db = null, $serverIndex ) {
738  if ( !$db ) {
739  $this->markServerDown( $exception, $serverIndex );
740  } elseif ( $db->wasReadOnlyError() ) {
741  if ( $db->trxLevel() && $this->usesMainDB() ) {
742  // Errors like deadlocks and connection drops already cause rollback.
743  // For consistency, we have no choice but to throw an error and trigger
744  // complete rollback if the main DB is also being used as the cache DB.
745  throw $exception;
746  }
747  }
748 
749  $this->logger->error( "DBError: {$exception->getMessage()}" );
750  if ( $exception instanceof DBConnectionError ) {
752  $this->logger->debug( __METHOD__ . ": ignoring connection error" );
753  } else {
755  $this->logger->debug( __METHOD__ . ": ignoring query error" );
756  }
757  }
758 
765  protected function markServerDown( DBError $exception, $serverIndex ) {
766  unset( $this->conns[$serverIndex] ); // bug T103435
767 
768  if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
769  if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
770  unset( $this->connFailureTimes[$serverIndex] );
771  unset( $this->connFailureErrors[$serverIndex] );
772  } else {
773  $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
774  return;
775  }
776  }
777  $now = time();
778  $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
779  $this->connFailureTimes[$serverIndex] = $now;
780  $this->connFailureErrors[$serverIndex] = $exception;
781  }
782 
786  public function createTables() {
787  for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
788  $db = $this->getDB( $serverIndex );
789  if ( $db->getType() !== 'mysql' ) {
790  throw new MWException( __METHOD__ . ' is not supported on this DB server' );
791  }
792 
793  for ( $i = 0; $i < $this->shards; $i++ ) {
794  $db->query(
795  'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
796  ' LIKE ' . $db->tableName( 'objectcache' ),
797  __METHOD__ );
798  }
799  }
800  }
801 
805  protected function usesMainDB() {
806  return !$this->serverInfos;
807  }
808 
809  protected function waitForReplication() {
810  if ( !$this->usesMainDB() ) {
811  // Custom DB server list; probably doesn't use replication
812  return true;
813  }
814 
815  $lb = $this->getSeparateMainLB()
816  ?: MediaWikiServices::getInstance()->getDBLoadBalancer();
817 
818  if ( $lb->getServerCount() <= 1 ) {
819  return true; // no replica DBs
820  }
821 
822  // Main LB is used; wait for any replica DBs to catch up
823  $masterPos = $lb->getMasterPos();
824 
825  $loop = new WaitConditionLoop(
826  function () use ( $lb, $masterPos ) {
827  return $lb->waitForAll( $masterPos, 1 );
828  },
831  );
832 
833  return ( $loop->invoke() === $loop::CONDITION_REACHED );
834  }
835 }
SqlBagOStuff\__construct
__construct( $params)
Constructor.
Definition: SqlBagOStuff.php:104
SqlBagOStuff\createTables
createTables()
Create shard tables.
Definition: SqlBagOStuff.php:786
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:45
SqlBagOStuff\doGet
doGet( $key, $flags=0)
Definition: SqlBagOStuff.php:249
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\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:498
BagOStuff\ERR_UNREACHABLE
const ERR_UNREACHABLE
Definition: BagOStuff.php:79
SqlBagOStuff\changeTTL
changeTTL( $key, $expiry=0)
Reset the TTL on a key if it exists.
Definition: SqlBagOStuff.php:507
SqlBagOStuff\$lastExpireAll
int $lastExpireAll
Definition: SqlBagOStuff.php:47
SqlBagOStuff\serialize
serialize(&$data)
Serialize an object and, if possible, compress the representation.
Definition: SqlBagOStuff.php:678
SqlBagOStuff\$separateMainLB
LoadBalancer null $separateMainLB
Definition: SqlBagOStuff.php:60
captcha-old.count
count
Definition: captcha-old.py:225
SqlBagOStuff\$serverInfos
array[] $serverInfos
(server index => server config)
Definition: SqlBagOStuff.php:41
SqlBagOStuff\getSeparateMainLB
getSeparateMainLB()
Definition: SqlBagOStuff.php:148
SqlBagOStuff\$conns
array $conns
Definition: SqlBagOStuff.php:62
$wgDBtype
$wgDBtype
Database type.
Definition: DefaultSettings.php:1775
IExpiringStore\QOS_EMULATION_SQL
const QOS_EMULATION_SQL
Definition: IExpiringStore.php:49
$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 '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1954
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1994
SqlBagOStuff\incr
incr( $key, $step=1)
Increase stored value of $key by $value while preserving its TTL.
Definition: SqlBagOStuff.php:453
BagOStuff\convertExpiry
convertExpiry( $exptime)
Convert an optionally relative time to an absolute time.
Definition: BagOStuff.php:692
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
BagOStuff\debug
debug( $text)
Definition: BagOStuff.php:679
$params
$params
Definition: styleTest.css.php:40
BagOStuff
interface is intended to be more or less compatible with the PHP memcached client.
Definition: BagOStuff.php:47
$res
$res
Definition: database.txt:21
$type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
$lbFactory
$lbFactory
Definition: doMaintenance.php:117
SqlBagOStuff\handleWriteError
handleWriteError(DBError $exception, IDatabase $db=null, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
Definition: SqlBagOStuff.php:737
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:40
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:216
key
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition: design.txt:25
SqlBagOStuff\$syncTimeout
int $syncTimeout
Definition: SqlBagOStuff.php:57
SqlBagOStuff\expireAll
expireAll()
Definition: SqlBagOStuff.php:567
MWException
MediaWiki exception.
Definition: MWException.php:26
SqlBagOStuff\deleteAll
deleteAll()
Delete content of shard tables in every server.
Definition: SqlBagOStuff.php:654
SqlBagOStuff\getDB
getDB( $serverIndex)
Get a connection to the specified database.
Definition: SqlBagOStuff.php:171
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
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
SqlBagOStuff\$connFailureErrors
array $connFailureErrors
Exceptions.
Definition: SqlBagOStuff.php:66
$tag
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:1028
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:264
SqlBagOStuff\handleReadError
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
Definition: SqlBagOStuff.php:715
IExpiringStore\QOS_SYNCWRITES_BE
const QOS_SYNCWRITES_BE
Definition: IExpiringStore.php:53
SqlBagOStuff\cas
cas( $casToken, $key, $value, $exptime=0)
Check and set an item.
Definition: SqlBagOStuff.php:395
SqlBagOStuff\isExpired
isExpired( $db, $exptime)
Definition: SqlBagOStuff.php:534
SqlBagOStuff\$tableName
string $tableName
Definition: SqlBagOStuff.php:53
BagOStuff\$busyCallbacks
callable[] $busyCallbacks
Definition: BagOStuff.php:71
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:2023
DB_MASTER
const DB_MASTER
Definition: defines.php:26
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:809
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
SqlBagOStuff\garbageCollect
garbageCollect()
Definition: SqlBagOStuff.php:550
$value
$value
Definition: styleTest.css.php:45
SqlBagOStuff\unserialize
unserialize( $serial)
Unserialize and, if necessary, decompress an object.
Definition: SqlBagOStuff.php:693
SqlBagOStuff\deleteObjectsExpiringBefore
deleteObjectsExpiringBefore( $timestamp, $progressCallback=false)
Delete objects from the database which expire before a certain date.
Definition: SqlBagOStuff.php:577
SqlBagOStuff\$connFailureTimes
array $connFailureTimes
UNIX timestamps.
Definition: SqlBagOStuff.php:64
IExpiringStore\ATTR_SYNCWRITES
const ATTR_SYNCWRITES
Definition: IExpiringStore.php:51
$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:1956
SqlBagOStuff\$numServers
int $numServers
Definition: SqlBagOStuff.php:45
BagOStuff\mergeViaCas
mergeViaCas( $key, $callback, $exptime=0, $attempts=10)
Definition: BagOStuff.php:289
SqlBagOStuff
Class to store objects in the database.
Definition: SqlBagOStuff.php:39
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:542
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
$keys
$keys
Definition: testCompression.php:65
SqlBagOStuff\setMulti
setMulti(array $data, $expiry=0)
Batch insertion.
Definition: SqlBagOStuff.php:326
SqlBagOStuff\getWithToken
getWithToken( $key, &$casToken, $flags=0)
Definition: SqlBagOStuff.php:255
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
Wikimedia\Rdbms\TransactionProfiler
Helper class that detects high-contention DB queries via profiling calls.
Definition: TransactionProfiler.php:39
IExpiringStore\QOS_SYNCWRITES_NONE
const QOS_SYNCWRITES_NONE
Definition: IExpiringStore.php:52
SqlBagOStuff\markServerDown
markServerDown(DBError $exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
Definition: SqlBagOStuff.php:765
BagOStuff\setLastError
setLastError( $err)
Set the "last error" registry.
Definition: BagOStuff.php:630
SqlBagOStuff\$purgePeriod
int $purgePeriod
Definition: SqlBagOStuff.php:49
BagOStuff\ERR_UNEXPECTED
const ERR_UNEXPECTED
Definition: BagOStuff.php:80
SqlBagOStuff\usesMainDB
usesMainDB()
Definition: SqlBagOStuff.php:805
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749
SqlBagOStuff\$shards
int $shards
Definition: SqlBagOStuff.php:51
array
the array() calling protocol came about after MediaWiki 1.4rc1.
SqlBagOStuff\getTableNameByShard
getTableNameByShard( $index)
Get the table name for a given shard index.
Definition: SqlBagOStuff.php:239