Go to the documentation of this file.
26 require __DIR__ .
'/../commandLine.inc';
28 if ( count(
$args ) < 1 ) {
29 echo
"Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
30 Moves blobs indexed by trackBlobs.php to a specified list of destination clusters, and recompresses them in the process. Restartable.
33 --procs <procs> Set the number of child processes (default 1)
34 --copy-only Copy only, do not update the text table. Restart without this option to complete.
35 --debug-log <file> Log debugging data to the specified file
36 --info-log <file> Log progress messages to the specified file
37 --critical-log <file> Log error messages to the specified file
68 'no-count' =>
'noCount',
69 'procs' =>
'numProcs',
70 'copy-only' =>
'copyOnly',
72 'slave-id' =>
'slaveId',
73 'debug-log' =>
'debugLog',
74 'info-log' =>
'infoLog',
75 'critical-log' =>
'criticalLog',
83 $jobOptions =
array(
'destClusters' =>
$args );
84 foreach ( self::$cmdLineOptionMap
as $cmdOption => $classOption ) {
85 if ( isset(
$options[$cmdOption] ) ) {
86 $jobOptions[$classOption] =
$options[$cmdOption];
89 return new self( $jobOptions );
97 if ( !$this->isChild ) {
98 $GLOBALS[
'wgDebugLogPrefix'] =
"RCT M: ";
99 } elseif ( $this->slaveId !==
false ) {
100 $GLOBALS[
'wgDebugLogPrefix'] =
"RCT {$this->slaveId}: ";
102 $this->useDiff = function_exists(
'xdiff_string_bdiff' );
103 $this->pageBlobClass = $this->useDiff ?
'DiffHistoryBlob' :
'ConcatenatedGzipHistoryBlob';
104 $this->orphanBlobClass =
'ConcatenatedGzipHistoryBlob';
109 if ( $this->debugLog ) {
110 $this->
logToFile( $msg, $this->debugLog );
117 if ( $this->infoLog ) {
118 $this->
logToFile( $msg, $this->infoLog );
124 if ( $this->criticalLog ) {
125 $this->
logToFile( $msg, $this->criticalLog );
130 $header =
'[' . date(
'd\TH:i:s' ) .
'] ' .
wfHostname() .
' ' . posix_getpid();
131 if ( $this->slaveId !==
false ) {
132 $header .=
"({$this->slaveId})";
146 $pos = $dbw->getMasterPos();
147 $dbr->masterPosWait( $pos, 100000 );
154 if ( $this->isChild ) {
182 if ( !
$dbr->tableExists(
'blob_tracking' ) ) {
183 $this->
critical(
"Error: blob_tracking table does not exist" );
186 $row =
$dbr->selectRow(
'blob_tracking',
'*',
false, __METHOD__ );
188 $this->
info(
"Warning: blob_tracking table contains no rows, skipping this wiki." );
202 foreach ( self::$cmdLineOptionMap
as $cmdOption => $classOption ) {
203 if ( $cmdOption ==
'slave-id' ) {
207 } elseif ( $this->$classOption ) {
208 $cmd .=
" --$cmdOption";
213 ' ' . call_user_func_array(
'wfEscapeShellArg', $this->destClusters );
215 $this->slavePipes = $this->slaveProcs =
array();
219 array(
'pipe',
'r' ),
220 array(
'file',
'php://stdout',
'w' ),
221 array(
'file',
'php://stderr',
'w' )
224 $proc = proc_open(
"$cmd --slave-id $i", $spec, $pipes );
227 $this->
critical(
"Error opening slave process: $cmd" );
230 $this->slaveProcs[$i] = $proc;
231 $this->slavePipes[$i] = $pipes[0];
233 $this->prevSlaveId = -1;
240 $this->
info(
"Waiting for slave processes to finish..." );
245 $status = proc_close( $this->slaveProcs[$i] );
247 $this->
critical(
"Warning: child #$i exited with status $status" );
250 $this->
info(
"Done." );
258 $args = func_get_args();
260 $numPipes = stream_select( $x =
array(), $pipes, $y =
array(), 3600 );
262 $this->
critical(
"Error waiting to write to slaves. Aborting" );
266 $slaveId = ( $i + $this->prevSlaveId + 1 ) % $this->numProcs;
282 $cmd = implode(
' ',
$args );
283 fwrite( $this->slavePipes[
$slaveId],
"$cmd\n" );
293 if ( $this->noCount ) {
294 $numPages =
'[unknown]';
296 $numPages =
$dbr->selectField(
'blob_tracking',
297 'COUNT(DISTINCT bt_page)',
299 array(
'bt_moved' => 0 ),
303 if ( $this->copyOnly ) {
304 $this->
info(
"Copying pages..." );
306 $this->
info(
"Moving pages..." );
309 $res =
$dbr->select(
'blob_tracking',
313 'bt_page > ' .
$dbr->addQuotes( $startId )
318 'ORDER BY' =>
'bt_page',
319 'LIMIT' => $this->batchSize,
322 if ( !
$res->numRows() ) {
325 foreach (
$res as $row ) {
326 $this->
dispatch(
'doPage', $row->bt_page );
329 $startId = $row->bt_page;
330 $this->
report(
'pages', $i, $numPages );
332 $this->
report(
'pages', $i, $numPages );
333 if ( $this->copyOnly ) {
334 $this->
info(
"All page copies queued." );
336 $this->
info(
"All page moves queued." );
343 function report( $label, $current, $end ) {
345 if ( $current == $end || $this->numBatches >= $this->reportingInterval ) {
346 $this->numBatches = 0;
347 $this->
info(
"$label: $current / $end" );
359 if ( $this->noCount ) {
360 $numOrphans =
'[unknown]';
362 $numOrphans =
$dbr->selectField(
'blob_tracking',
363 'COUNT(DISTINCT bt_text_id)',
364 array(
'bt_moved' => 0,
'bt_page' => 0 ),
366 if ( !$numOrphans ) {
370 if ( $this->copyOnly ) {
371 $this->
info(
"Copying orphans..." );
373 $this->
info(
"Moving orphans..." );
377 $res =
$dbr->select(
'blob_tracking',
378 array(
'bt_text_id' ),
382 'bt_text_id > ' .
$dbr->addQuotes( $startId )
387 'ORDER BY' =>
'bt_text_id',
388 'LIMIT' => $this->batchSize
391 if ( !
$res->numRows() ) {
395 foreach (
$res as $row ) {
396 $ids[] = $row->bt_text_id;
402 while ( count( $ids ) > $this->orphanBatchSize ) {
403 $args = array_slice( $ids, 0, $this->orphanBatchSize );
404 $ids = array_slice( $ids, $this->orphanBatchSize );
405 array_unshift(
$args,
'doOrphanList' );
406 call_user_func_array(
array( $this,
'dispatch' ),
$args );
408 if ( count( $ids ) ) {
410 array_unshift(
$args,
'doOrphanList' );
411 call_user_func_array(
array( $this,
'dispatch' ),
$args );
414 $startId = $row->bt_text_id;
415 $this->
report(
'orphans', $i, $numOrphans );
417 $this->
report(
'orphans', $i, $numOrphans );
418 $this->
info(
"All orphans queued." );
425 $this->
debug(
'starting' );
428 while ( !feof( STDIN ) ) {
429 $line = rtrim( fgets( STDIN ) );
435 $cmd = array_shift(
$args );
454 $title = Title::newFromId( $pageId );
456 $titleText =
$title->getPrefixedText();
458 $titleText =
'[deleted]';
463 if ( !$this->copyOnly ) {
473 array(
'blob_tracking',
'text' ),
476 'bt_page' => $pageId,
477 'bt_text_id > ' .
$dbr->addQuotes( $startId ),
479 'bt_new_url IS NULL',
484 'ORDER BY' =>
'bt_text_id',
485 'LIMIT' => $this->batchSize
488 if ( !
$res->numRows() ) {
493 foreach (
$res as $row ) {
494 if ( $lastTextId == $row->bt_text_id ) {
498 $lastTextId = $row->bt_text_id;
501 if ( $text ===
false ) {
502 $this->
critical(
"Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
507 if ( !$trx->addItem( $text, $row->bt_text_id ) ) {
508 $this->
debug(
"$titleText: committing blob with " . $trx->getSize() .
" items" );
514 $startId = $row->bt_text_id;
517 $this->
debug(
"$titleText: committing blob with " . $trx->getSize() .
" items" );
532 if ( $this->copyOnly ) {
533 $this->
critical(
"Internal error: can't call moveTextRow() in --copy-only mode" );
537 $dbw->begin( __METHOD__ );
538 $dbw->update(
'text',
541 'old_flags' =>
'external,utf-8',
548 $dbw->update(
'blob_tracking',
549 array(
'bt_moved' => 1 ),
550 array(
'bt_text_id' => $textId ),
553 $dbw->commit( __METHOD__ );
568 $conds = array_merge( $conds,
array(
570 'bt_new_url IS NOT NULL'
573 $res =
$dbr->select(
'blob_tracking',
575 array_merge( $conds,
array(
'bt_text_id > ' .
$dbr->addQuotes( $startId ) ) ),
578 'ORDER BY' =>
'bt_text_id',
579 'LIMIT' => $this->batchSize,
582 if ( !
$res->numRows() ) {
585 $this->
debug(
'Incomplete: ' .
$res->numRows() .
' rows' );
586 foreach (
$res as $row ) {
587 $this->
moveTextRow( $row->bt_text_id, $row->bt_new_url );
588 if ( $row->bt_text_id % 10 == 0 ) {
592 $startId = $row->bt_text_id;
601 $cluster = next( $this->destClusters );
602 if ( $cluster ===
false ) {
603 $cluster = reset( $this->destClusters );
623 if ( !$this->copyOnly ) {
631 array(
'text',
'blob_tracking' ),
632 array(
'old_id',
'old_text',
'old_flags' ),
634 'old_id' => $textIds,
642 foreach (
$res as $row ) {
644 if ( $text ===
false ) {
645 $this->
critical(
"Error: cannot load revision text for old_id={$row->old_id}" );
649 if ( !$trx->addItem( $text, $row->old_id ) ) {
650 $this->
debug(
"[orphan]: committing blob with " . $trx->getSize() .
" rows" );
656 $this->
debug(
"[orphan]: committing blob with " . $trx->getSize() .
" rows" );
666 list( $host, $maxLag ) =
$lb->getMaxLag();
690 $this->texts =
array();
704 $this->cgz =
new $class;
706 $hash = $this->cgz->addItem( $text );
707 $this->referrers[$textId] =
$hash;
708 $this->texts[$textId] = $text;
709 return $this->cgz->isHappy();
713 return count( $this->texts );
721 $this->cgz =
new $class;
722 $this->referrers =
array();
723 foreach ( $this->texts
as $textId => $text ) {
724 $hash = $this->cgz->addItem( $text );
725 $this->referrers[$textId] =
$hash;
735 $originalCount = count( $this->texts );
736 if ( !$originalCount ) {
748 $dbw->begin( __METHOD__ );
749 $res = $dbw->select(
'blob_tracking',
750 array(
'bt_text_id',
'bt_moved' ),
751 array(
'bt_text_id' => array_keys( $this->referrers ) ),
752 __METHOD__,
array(
'FOR UPDATE' ) );
754 foreach (
$res as $row ) {
755 if ( $row->bt_moved ) {
756 # This row has already been moved, remove it
757 $this->parent->debug(
"TRX: conflict detected in old_id={$row->bt_text_id}" );
758 unset( $this->texts[$row->bt_text_id] );
765 if ( !count( $this->texts ) ) {
767 if ( $originalCount > 1 ) {
769 $this->critical(
"Warning: concurrent operation detected, are there two conflicting " .
770 "processes running, doing the same job?" );
778 $targetCluster = $this->parent->getTargetCluster();
779 $store = $this->parent->store;
780 $targetDB = $store->getMaster( $targetCluster );
781 $targetDB->clearFlag(
DBO_TRX );
782 $targetDB->begin( __METHOD__ );
783 $baseUrl = $this->parent->store->store( $targetCluster, serialize( $this->cgz ) );
786 foreach ( $this->referrers
as $textId =>
$hash ) {
787 $url = $baseUrl .
'/' .
$hash;
788 $dbw->update(
'blob_tracking',
789 array(
'bt_new_url' => $url ),
791 'bt_text_id' => $textId,
792 'bt_moved' => 0, # Check
for concurrent conflicting update
798 $targetDB->commit( __METHOD__ );
801 $dbw->commit( __METHOD__ );
804 if ( !$this->parent->copyOnly ) {
805 foreach ( $this->referrers
as $textId =>
$hash ) {
806 $url = $baseUrl .
'/' .
$hash;
807 $this->parent->moveTextRow( $textId, $url );
wfErrorLog( $text, $file)
Log to a file without getting "file size exceeded" signals.
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Maintenance script that moves blobs indexed by trackBlobs.php to a specified list of destination clus...
DB accessable external objects.
addItem( $text, $textId)
Add text.
killSlaveProcs()
Gracefully terminate the child processes.
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
wfGetLB( $wiki=false)
Get a load balancer object.
& wfGetDB( $db, $groups=array(), $wiki=false)
Get a Database object.
getTargetCluster()
Returns the name of the next target cluster.
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
wfHostname()
Fetch server name for use in error reporting etc.
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row $row is usually an object from wfFetchRow(),...
recompress()
Recompress text after some aberrant modification.
getExtDB( $cluster)
Gets a DB master connection for the given external cluster name.
executeParent()
Execute the parent process.
if( $wgAPIRequestLog) $lb
wfRestoreWarnings()
Restore error level to previous value.
I won t presume to tell you how to I m just describing the methods I chose to use for myself If you do choose to follow these it will probably be easier for you to collaborate with others on the but if you want to contribute without by all means do so(and don 't be surprised if I reformat your code). - I have the code indented with tabs to save file size and so that users can set their tab stops to any depth they like. I use 4-space tab stops
finishIncompleteMoves( $conds)
Moves are done in two phases: bt_new_url and then bt_moved.
doPage( $pageId)
Move tracked text in a given page.
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
static newFromCommandLine( $args, $options)
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
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 & $options
doAllOrphans()
Move all orphan text to the new clusters.
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
presenting them properly to the user as errors is done by the caller $title
Allows to change the fields on the form that will be generated $name
waitForSlaves()
Wait for slaves (quietly)
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell,...
Class to represent a recompression operation for a single CGZ blob.
report( $label, $current, $end)
Display a progress report.
moveTextRow( $textId, $url)
Atomic move operation.
__construct( $parent, $blobClass)
Create a transaction from a RecompressTracked object.
dispatchToSlave( $slaveId, $args)
Dispatch a command to a specified slave.
executeChild()
Main entry point for worker processes.
return false to override stock group addition can be modified try getUserPermissionsErrors userCan checks are continued by internal code can override on output return false to not delete it return false to override the default password checks & $hash
if(PHP_SAPI !='cli') $file
checkTrackingTable()
Make sure the tracking table exists and isn't empty.
execute()
Execute parent or child depending on the isChild option.
& wfGetLBFactory()
Get the load balancer factory object.
if(count( $args)< 1) $job
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
doAllPages()
Move all tracked pages to the new clusters.
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
dispatch()
Dispatch a command to the next available slave.
syncDBs()
Wait until the selected slave has caught up to the master.
startSlaveProcs()
Start the worker processes.
doOrphanList( $textIds)
Move an orphan text_id to the new cluster.
static getOptionsWithArgs()