MediaWiki  1.27.2
recompressTracked.php
Go to the documentation of this file.
1 <?php
26 
28 require __DIR__ . '/../commandLine.inc';
29 
30 if ( count( $args ) < 1 ) {
31  echo "Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
32 Moves blobs indexed by trackBlobs.php to a specified list of destination clusters,
33 and recompresses them in the process. Restartable.
34 
35 Options:
36  --procs <procs> Set the number of child processes (default 1)
37  --copy-only Copy only, do not update the text table. Restart
38  without this option to complete.
39  --debug-log <file> Log debugging data to the specified file
40  --info-log <file> Log progress messages to the specified file
41  --critical-log <file> Log error messages to the specified file
42 ";
43  exit( 1 );
44 }
45 
47 $job->execute();
48 
56  public $destClusters;
57  public $batchSize = 1000;
58  public $orphanBatchSize = 1000;
59  public $reportingInterval = 10;
60  public $numProcs = 1;
61  public $numBatches = 0;
64  public $copyOnly = false;
65  public $isChild = false;
66  public $slaveId = false;
67  public $noCount = false;
69  public $store;
70 
71  private static $optionsWithArgs = [
72  'procs',
73  'slave-id',
74  'debug-log',
75  'info-log',
76  'critical-log'
77  ];
78 
79  private static $cmdLineOptionMap = [
80  'no-count' => 'noCount',
81  'procs' => 'numProcs',
82  'copy-only' => 'copyOnly',
83  'child' => 'isChild',
84  'slave-id' => 'slaveId',
85  'debug-log' => 'debugLog',
86  'info-log' => 'infoLog',
87  'critical-log' => 'criticalLog',
88  ];
89 
90  static function getOptionsWithArgs() {
92  }
93 
94  static function newFromCommandLine( $args, $options ) {
95  $jobOptions = [ 'destClusters' => $args ];
96  foreach ( self::$cmdLineOptionMap as $cmdOption => $classOption ) {
97  if ( isset( $options[$cmdOption] ) ) {
98  $jobOptions[$classOption] = $options[$cmdOption];
99  }
100  }
101 
102  return new self( $jobOptions );
103  }
104 
105  function __construct( $options ) {
106  foreach ( $options as $name => $value ) {
107  $this->$name = $value;
108  }
109  $this->store = new ExternalStoreDB;
110  if ( !$this->isChild ) {
111  $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
112  } elseif ( $this->slaveId !== false ) {
113  $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
114  }
115  $this->useDiff = function_exists( 'xdiff_string_bdiff' );
116  $this->pageBlobClass = $this->useDiff ? 'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
117  $this->orphanBlobClass = 'ConcatenatedGzipHistoryBlob';
118  }
119 
120  function debug( $msg ) {
121  wfDebug( "$msg\n" );
122  if ( $this->debugLog ) {
123  $this->logToFile( $msg, $this->debugLog );
124  }
125  }
126 
127  function info( $msg ) {
128  echo "$msg\n";
129  if ( $this->infoLog ) {
130  $this->logToFile( $msg, $this->infoLog );
131  }
132  }
133 
134  function critical( $msg ) {
135  echo "$msg\n";
136  if ( $this->criticalLog ) {
137  $this->logToFile( $msg, $this->criticalLog );
138  }
139  }
140 
141  function logToFile( $msg, $file ) {
142  $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
143  if ( $this->slaveId !== false ) {
144  $header .= "({$this->slaveId})";
145  }
146  $header .= ' ' . wfWikiID();
147  LegacyLogger::emit( sprintf( "%-50s %s\n", $header, $msg ), $file );
148  }
149 
155  function syncDBs() {
156  $dbw = wfGetDB( DB_MASTER );
157  $dbr = wfGetDB( DB_SLAVE );
158  $pos = $dbw->getMasterPos();
159  $dbr->masterPosWait( $pos, 100000 );
160  }
161 
165  function execute() {
166  if ( $this->isChild ) {
167  $this->executeChild();
168  } else {
169  $this->executeParent();
170  }
171  }
172 
176  function executeParent() {
177  if ( !$this->checkTrackingTable() ) {
178  return;
179  }
180 
181  $this->syncDBs();
182  $this->startSlaveProcs();
183  $this->doAllPages();
184  $this->doAllOrphans();
185  $this->killSlaveProcs();
186  }
187 
192  function checkTrackingTable() {
193  $dbr = wfGetDB( DB_SLAVE );
194  if ( !$dbr->tableExists( 'blob_tracking' ) ) {
195  $this->critical( "Error: blob_tracking table does not exist" );
196 
197  return false;
198  }
199  $row = $dbr->selectRow( 'blob_tracking', '*', '', __METHOD__ );
200  if ( !$row ) {
201  $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
202 
203  return false;
204  }
205 
206  return true;
207  }
208 
215  function startSlaveProcs() {
216  $cmd = 'php ' . wfEscapeShellArg( __FILE__ );
217  foreach ( self::$cmdLineOptionMap as $cmdOption => $classOption ) {
218  if ( $cmdOption == 'slave-id' ) {
219  continue;
220  } elseif ( in_array( $cmdOption, self::$optionsWithArgs ) && isset( $this->$classOption ) ) {
221  $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
222  } elseif ( $this->$classOption ) {
223  $cmd .= " --$cmdOption";
224  }
225  }
226  $cmd .= ' --child' .
227  ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
228  ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters );
229 
230  $this->slavePipes = $this->slaveProcs = [];
231  for ( $i = 0; $i < $this->numProcs; $i++ ) {
232  $pipes = [];
233  $spec = [
234  [ 'pipe', 'r' ],
235  [ 'file', 'php://stdout', 'w' ],
236  [ 'file', 'php://stderr', 'w' ]
237  ];
238  MediaWiki\suppressWarnings();
239  $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
240  MediaWiki\restoreWarnings();
241  if ( !$proc ) {
242  $this->critical( "Error opening slave process: $cmd" );
243  exit( 1 );
244  }
245  $this->slaveProcs[$i] = $proc;
246  $this->slavePipes[$i] = $pipes[0];
247  }
248  $this->prevSlaveId = -1;
249  }
250 
254  function killSlaveProcs() {
255  $this->info( "Waiting for slave processes to finish..." );
256  for ( $i = 0; $i < $this->numProcs; $i++ ) {
257  $this->dispatchToSlave( $i, 'quit' );
258  }
259  for ( $i = 0; $i < $this->numProcs; $i++ ) {
260  $status = proc_close( $this->slaveProcs[$i] );
261  if ( $status ) {
262  $this->critical( "Warning: child #$i exited with status $status" );
263  }
264  }
265  $this->info( "Done." );
266  }
267 
272  function dispatch( /*...*/ ) {
273  $args = func_get_args();
274  $pipes = $this->slavePipes;
275  $numPipes = stream_select( $x = [], $pipes, $y = [], 3600 );
276  if ( !$numPipes ) {
277  $this->critical( "Error waiting to write to slaves. Aborting" );
278  exit( 1 );
279  }
280  for ( $i = 0; $i < $this->numProcs; $i++ ) {
281  $slaveId = ( $i + $this->prevSlaveId + 1 ) % $this->numProcs;
282  if ( isset( $pipes[$slaveId] ) ) {
283  $this->prevSlaveId = $slaveId;
284  $this->dispatchToSlave( $slaveId, $args );
285 
286  return;
287  }
288  }
289  $this->critical( "Unreachable" );
290  exit( 1 );
291  }
292 
299  $args = (array)$args;
300  $cmd = implode( ' ', $args );
301  fwrite( $this->slavePipes[$slaveId], "$cmd\n" );
302  }
303 
307  function doAllPages() {
308  $dbr = wfGetDB( DB_SLAVE );
309  $i = 0;
310  $startId = 0;
311  if ( $this->noCount ) {
312  $numPages = '[unknown]';
313  } else {
314  $numPages = $dbr->selectField( 'blob_tracking',
315  'COUNT(DISTINCT bt_page)',
316  # A condition is required so that this query uses the index
317  [ 'bt_moved' => 0 ],
318  __METHOD__
319  );
320  }
321  if ( $this->copyOnly ) {
322  $this->info( "Copying pages..." );
323  } else {
324  $this->info( "Moving pages..." );
325  }
326  while ( true ) {
327  $res = $dbr->select( 'blob_tracking',
328  [ 'bt_page' ],
329  [
330  'bt_moved' => 0,
331  'bt_page > ' . $dbr->addQuotes( $startId )
332  ],
333  __METHOD__,
334  [
335  'DISTINCT',
336  'ORDER BY' => 'bt_page',
337  'LIMIT' => $this->batchSize,
338  ]
339  );
340  if ( !$res->numRows() ) {
341  break;
342  }
343  foreach ( $res as $row ) {
344  $startId = $row->bt_page;
345  $this->dispatch( 'doPage', $row->bt_page );
346  $i++;
347  }
348  $this->report( 'pages', $i, $numPages );
349  }
350  $this->report( 'pages', $i, $numPages );
351  if ( $this->copyOnly ) {
352  $this->info( "All page copies queued." );
353  } else {
354  $this->info( "All page moves queued." );
355  }
356  }
357 
364  function report( $label, $current, $end ) {
365  $this->numBatches++;
366  if ( $current == $end || $this->numBatches >= $this->reportingInterval ) {
367  $this->numBatches = 0;
368  $this->info( "$label: $current / $end" );
369  wfWaitForSlaves();
370  }
371  }
372 
376  function doAllOrphans() {
377  $dbr = wfGetDB( DB_SLAVE );
378  $startId = 0;
379  $i = 0;
380  if ( $this->noCount ) {
381  $numOrphans = '[unknown]';
382  } else {
383  $numOrphans = $dbr->selectField( 'blob_tracking',
384  'COUNT(DISTINCT bt_text_id)',
385  [ 'bt_moved' => 0, 'bt_page' => 0 ],
386  __METHOD__ );
387  if ( !$numOrphans ) {
388  return;
389  }
390  }
391  if ( $this->copyOnly ) {
392  $this->info( "Copying orphans..." );
393  } else {
394  $this->info( "Moving orphans..." );
395  }
396 
397  while ( true ) {
398  $res = $dbr->select( 'blob_tracking',
399  [ 'bt_text_id' ],
400  [
401  'bt_moved' => 0,
402  'bt_page' => 0,
403  'bt_text_id > ' . $dbr->addQuotes( $startId )
404  ],
405  __METHOD__,
406  [
407  'DISTINCT',
408  'ORDER BY' => 'bt_text_id',
409  'LIMIT' => $this->batchSize
410  ]
411  );
412  if ( !$res->numRows() ) {
413  break;
414  }
415  $ids = [];
416  foreach ( $res as $row ) {
417  $startId = $row->bt_text_id;
418  $ids[] = $row->bt_text_id;
419  $i++;
420  }
421  // Need to send enough orphan IDs to the child at a time to fill a blob,
422  // so orphanBatchSize needs to be at least ~100.
423  // batchSize can be smaller or larger.
424  while ( count( $ids ) > $this->orphanBatchSize ) {
425  $args = array_slice( $ids, 0, $this->orphanBatchSize );
426  $ids = array_slice( $ids, $this->orphanBatchSize );
427  array_unshift( $args, 'doOrphanList' );
428  call_user_func_array( [ $this, 'dispatch' ], $args );
429  }
430  if ( count( $ids ) ) {
431  $args = $ids;
432  array_unshift( $args, 'doOrphanList' );
433  call_user_func_array( [ $this, 'dispatch' ], $args );
434  }
435 
436  $this->report( 'orphans', $i, $numOrphans );
437  }
438  $this->report( 'orphans', $i, $numOrphans );
439  $this->info( "All orphans queued." );
440  }
441 
445  function executeChild() {
446  $this->debug( 'starting' );
447  $this->syncDBs();
448 
449  while ( !feof( STDIN ) ) {
450  $line = rtrim( fgets( STDIN ) );
451  if ( $line == '' ) {
452  continue;
453  }
454  $this->debug( $line );
455  $args = explode( ' ', $line );
456  $cmd = array_shift( $args );
457  switch ( $cmd ) {
458  case 'doPage':
459  $this->doPage( intval( $args[0] ) );
460  break;
461  case 'doOrphanList':
462  $this->doOrphanList( array_map( 'intval', $args ) );
463  break;
464  case 'quit':
465  return;
466  }
467  wfWaitForSlaves();
468  }
469  }
470 
476  function doPage( $pageId ) {
477  $title = Title::newFromID( $pageId );
478  if ( $title ) {
479  $titleText = $title->getPrefixedText();
480  } else {
481  $titleText = '[deleted]';
482  }
483  $dbr = wfGetDB( DB_SLAVE );
484 
485  // Finish any incomplete transactions
486  if ( !$this->copyOnly ) {
487  $this->finishIncompleteMoves( [ 'bt_page' => $pageId ] );
488  $this->syncDBs();
489  }
490 
491  $startId = 0;
492  $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
493 
494  while ( true ) {
495  $res = $dbr->select(
496  [ 'blob_tracking', 'text' ],
497  '*',
498  [
499  'bt_page' => $pageId,
500  'bt_text_id > ' . $dbr->addQuotes( $startId ),
501  'bt_moved' => 0,
502  'bt_new_url IS NULL',
503  'bt_text_id=old_id',
504  ],
505  __METHOD__,
506  [
507  'ORDER BY' => 'bt_text_id',
508  'LIMIT' => $this->batchSize
509  ]
510  );
511  if ( !$res->numRows() ) {
512  break;
513  }
514 
515  $lastTextId = 0;
516  foreach ( $res as $row ) {
517  $startId = $row->bt_text_id;
518  if ( $lastTextId == $row->bt_text_id ) {
519  // Duplicate (null edit)
520  continue;
521  }
522  $lastTextId = $row->bt_text_id;
523  // Load the text
524  $text = Revision::getRevisionText( $row );
525  if ( $text === false ) {
526  $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
527  continue;
528  }
529 
530  // Queue it
531  if ( !$trx->addItem( $text, $row->bt_text_id ) ) {
532  $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
533  $trx->commit();
534  $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
535  wfWaitForSlaves();
536  }
537  }
538  }
539 
540  $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
541  $trx->commit();
542  }
543 
557  function moveTextRow( $textId, $url ) {
558  if ( $this->copyOnly ) {
559  $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
560  exit( 1 );
561  }
562  $dbw = wfGetDB( DB_MASTER );
563  $dbw->begin( __METHOD__ );
564  $dbw->update( 'text',
565  [ // set
566  'old_text' => $url,
567  'old_flags' => 'external,utf-8',
568  ],
569  [ // where
570  'old_id' => $textId
571  ],
572  __METHOD__
573  );
574  $dbw->update( 'blob_tracking',
575  [ 'bt_moved' => 1 ],
576  [ 'bt_text_id' => $textId ],
577  __METHOD__
578  );
579  $dbw->commit( __METHOD__ );
580  }
581 
592  function finishIncompleteMoves( $conds ) {
593  $dbr = wfGetDB( DB_SLAVE );
594 
595  $startId = 0;
596  $conds = array_merge( $conds, [
597  'bt_moved' => 0,
598  'bt_new_url IS NOT NULL'
599  ] );
600  while ( true ) {
601  $res = $dbr->select( 'blob_tracking',
602  '*',
603  array_merge( $conds, [ 'bt_text_id > ' . $dbr->addQuotes( $startId ) ] ),
604  __METHOD__,
605  [
606  'ORDER BY' => 'bt_text_id',
607  'LIMIT' => $this->batchSize,
608  ]
609  );
610  if ( !$res->numRows() ) {
611  break;
612  }
613  $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
614  foreach ( $res as $row ) {
615  $startId = $row->bt_text_id;
616  $this->moveTextRow( $row->bt_text_id, $row->bt_new_url );
617  if ( $row->bt_text_id % 10 == 0 ) {
618  wfWaitForSlaves();
619  }
620  }
621  }
622  }
623 
628  function getTargetCluster() {
629  $cluster = next( $this->destClusters );
630  if ( $cluster === false ) {
631  $cluster = reset( $this->destClusters );
632  }
633 
634  return $cluster;
635  }
636 
642  function getExtDB( $cluster ) {
643  $lb = wfGetLBFactory()->getExternalLB( $cluster );
644 
645  return $lb->getConnection( DB_MASTER );
646  }
647 
653  function doOrphanList( $textIds ) {
654  // Finish incomplete moves
655  if ( !$this->copyOnly ) {
656  $this->finishIncompleteMoves( [ 'bt_text_id' => $textIds ] );
657  $this->syncDBs();
658  }
659 
660  $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
661 
662  $res = wfGetDB( DB_SLAVE )->select(
663  [ 'text', 'blob_tracking' ],
664  [ 'old_id', 'old_text', 'old_flags' ],
665  [
666  'old_id' => $textIds,
667  'bt_text_id=old_id',
668  'bt_moved' => 0,
669  ],
670  __METHOD__,
671  [ 'DISTINCT' ]
672  );
673 
674  foreach ( $res as $row ) {
675  $text = Revision::getRevisionText( $row );
676  if ( $text === false ) {
677  $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
678  continue;
679  }
680 
681  if ( !$trx->addItem( $text, $row->old_id ) ) {
682  $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
683  $trx->commit();
684  $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
685  wfWaitForSlaves();
686  }
687  }
688  $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
689  $trx->commit();
690  }
691 }
692 
698  public $parent;
699  public $blobClass;
701  public $cgz;
702  public $referrers;
703 
710  $this->blobClass = $blobClass;
711  $this->cgz = false;
712  $this->texts = [];
713  $this->parent = $parent;
714  }
715 
723  function addItem( $text, $textId ) {
724  if ( !$this->cgz ) {
725  $class = $this->blobClass;
726  $this->cgz = new $class;
727  }
728  $hash = $this->cgz->addItem( $text );
729  $this->referrers[$textId] = $hash;
730  $this->texts[$textId] = $text;
731 
732  return $this->cgz->isHappy();
733  }
734 
735  function getSize() {
736  return count( $this->texts );
737  }
738 
742  function recompress() {
743  $class = $this->blobClass;
744  $this->cgz = new $class;
745  $this->referrers = [];
746  foreach ( $this->texts as $textId => $text ) {
747  $hash = $this->cgz->addItem( $text );
748  $this->referrers[$textId] = $hash;
749  }
750  }
751 
757  function commit() {
758  $originalCount = count( $this->texts );
759  if ( !$originalCount ) {
760  return;
761  }
762 
763  /* Check to see if the target text_ids have been moved already.
764  *
765  * We originally read from the slave, so this can happen when a single
766  * text_id is shared between multiple pages. It's rare, but possible
767  * if a delete/move/undelete cycle splits up a null edit.
768  *
769  * We do a locking read to prevent closer-run race conditions.
770  */
771  $dbw = wfGetDB( DB_MASTER );
772  $dbw->begin( __METHOD__ );
773  $res = $dbw->select( 'blob_tracking',
774  [ 'bt_text_id', 'bt_moved' ],
775  [ 'bt_text_id' => array_keys( $this->referrers ) ],
776  __METHOD__, [ 'FOR UPDATE' ] );
777  $dirty = false;
778  foreach ( $res as $row ) {
779  if ( $row->bt_moved ) {
780  # This row has already been moved, remove it
781  $this->parent->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
782  unset( $this->texts[$row->bt_text_id] );
783  $dirty = true;
784  }
785  }
786 
787  // Recompress the blob if necessary
788  if ( $dirty ) {
789  if ( !count( $this->texts ) ) {
790  // All have been moved already
791  if ( $originalCount > 1 ) {
792  // This is suspcious, make noise
793  $this->parent->critical(
794  "Warning: concurrent operation detected, are there two conflicting " .
795  "processes running, doing the same job?" );
796  }
797 
798  return;
799  }
800  $this->recompress();
801  }
802 
803  // Insert the data into the destination cluster
804  $targetCluster = $this->parent->getTargetCluster();
805  $store = $this->parent->store;
806  $targetDB = $store->getMaster( $targetCluster );
807  $targetDB->clearFlag( DBO_TRX ); // we manage the transactions
808  $targetDB->begin( __METHOD__ );
809  $baseUrl = $this->parent->store->store( $targetCluster, serialize( $this->cgz ) );
810 
811  // Write the new URLs to the blob_tracking table
812  foreach ( $this->referrers as $textId => $hash ) {
813  $url = $baseUrl . '/' . $hash;
814  $dbw->update( 'blob_tracking',
815  [ 'bt_new_url' => $url ],
816  [
817  'bt_text_id' => $textId,
818  'bt_moved' => 0, # Check for concurrent conflicting update
819  ],
820  __METHOD__
821  );
822  }
823 
824  $targetDB->commit( __METHOD__ );
825  // Critical section here: interruption at this point causes blob duplication
826  // Reversing the order of the commits would cause data loss instead
827  $dbw->commit( __METHOD__ );
828 
829  // Write the new URLs to the text table and set the moved flag
830  if ( !$this->parent->copyOnly ) {
831  foreach ( $this->referrers as $textId => $hash ) {
832  $url = $baseUrl . '/' . $hash;
833  $this->parent->moveTextRow( $textId, $url );
834  }
835  }
836  }
837 }
killSlaveProcs()
Gracefully terminate the child processes.
#define the
table suitable for use with IDatabase::select()
static newFromID($id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:417
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 then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if that
Definition: deferred.txt:11
MediaWiki Logger LegacyLogger
Definition: logger.txt:54
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
static getRevisionText($row, $prefix= 'old_', $wiki=false)
Get revision text associated with an old or archive row $row is usually an object from wfFetchRow()...
Definition: Revision.php:1231
wfWaitForSlaves($ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the slaves to catch up to the master position.
dispatchToSlave($slaveId, $args)
Dispatch a command to a specified slave.
dispatch()
Dispatch a command to the next available slave.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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 except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server.Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use.Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves.The master writes thequery to the binlog when the transaction is committed.The slaves pollthe binlog and start executing the query as soon as it appears.They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes.Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load.MediaWiki's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database.All edits and other write operations will berefused, with an error returned to the user.This gives the slaves achance to catch up.Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order.A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests.This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it.Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in"lagged slave mode".Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode().The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time.Multi-row INSERT...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it's not practical to guarantee a low-lagenvironment.Lag will usually be less than one second, but mayoccasionally be up to 30 seconds.For scalability, it's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer.So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum.In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks.By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent.Locks willbe held from the time when the query is done until the commit.So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction.Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
wfHostname()
Fetch server name for use in error reporting etc.
$value
const DBO_TRX
Definition: Defines.php:33
addItem($text, $textId)
Add text.
getTargetCluster()
Returns the name of the next target cluster.
RecompressTracked $parent
finishIncompleteMoves($conds)
Moves are done in two phases: bt_new_url and then bt_moved.
commit()
Commit the blob.
MediaWiki s SiteStore can be cached and stored in a flat in a json format If the SiteStore is frequently the file cache may provide a performance benefit over a database store
Definition: sitescache.txt:1
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
if($line===false) $args
Definition: cdb.php:64
executeParent()
Execute the parent process.
$GLOBALS['IP']
ConcatenatedGzipHistoryBlob $cgz
doAllOrphans()
Move all orphan text to the new clusters.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1004
$res
Definition: database.txt:21
doPage($pageId)
Move tracked text in a given page.
getExtDB($cluster)
Gets a DB master connection for the given external cluster name.
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 and or sell copies of the and to permit persons to whom the Software is furnished to do so
Definition: LICENSE.txt:10
static newFromCommandLine($args, $options)
const DB_SLAVE
Definition: Defines.php:46
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
$optionsWithArgs
Maintenance script that moves blobs indexed by trackBlobs.php to a specified list of destination clus...
executeChild()
Main entry point for worker processes.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
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
Class to represent a recompression operation for a single CGZ blob.
checkTrackingTable()
Make sure the tracking table exists and isn't empty.
report($label, $current, $end)
Display a progress report.
__construct($parent, $blobClass)
Create a transaction from a RecompressTracked object.
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
wfGetLBFactory()
Get the load balancer factory object.
doAllPages()
Move all tracked pages to the new clusters.
if(count($args)< 1) $job
$line
Definition: cdb.php:59
startSlaveProcs()
Start the worker processes.
recompress()
Recompress text after some aberrant modification.
static static getOptionsWithArgs()
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1004
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell...
const DB_MASTER
Definition: Defines.php:47
execute()
Execute parent or child depending on the isChild option.
serialize()
Definition: ApiMessage.php:94
DB accessable external objects.
doOrphanList($textIds)
Move an orphan text_id to the new cluster.
syncDBs()
Wait until the selected slave has caught up to the master.
For a write query
Definition: database.txt:26
moveTextRow($textId, $url)
Atomic move operation.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310