Typo
[lhc/web/wiklou.git] / maintenance / storage / recompressTracked.php
1 <?php
2
3 $optionsWithArgs = RecompressTracked::getOptionsWithArgs();
4 require( dirname( __FILE__ ) .'/../commandLine.inc' );
5
6 if ( count( $args ) < 1 ) {
7 echo "Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
8 Moves blobs indexed by trackBlobs.php to a specified list of destination clusters, and recompresses them in the process. Restartable.
9
10 Options:
11 --procs <procs> Set the number of child processes (default 8)
12 --copy-only Copy only, do not update the text table. Restart without this option to complete.
13 ";
14 exit( 1 );
15 }
16
17 $job = RecompressTracked::newFromCommandLine( $args, $options );
18 $job->execute();
19
20 class RecompressTracked {
21 var $destClusters;
22 var $batchSize = 1000;
23 var $reportingInterval = 10;
24 var $numProcs = 8;
25 var $useDiff, $pageBlobClass, $orphanBlobClass;
26 var $slavePipes, $slaveProcs, $prevSlaveId;
27 var $copyOnly = false;
28 var $isChild = false;
29 var $slaveId = false;
30 var $store;
31
32 static $optionsWithArgs = array( 'procs', 'slave-id' );
33 static $cmdLineOptionMap = array(
34 'procs' => 'numProcs',
35 'copy-only' => 'copyOnly',
36 'child' => 'isChild',
37 'slave-id' => 'slaveId',
38 );
39
40 static function getOptionsWithArgs() {
41 return self::$optionsWithArgs;
42 }
43
44 static function newFromCommandLine( $args, $options ) {
45 $jobOptions = array( 'destClusters' => $args );
46 foreach ( self::$cmdLineOptionMap as $cmdOption => $classOption ) {
47 if ( isset( $options[$cmdOption] ) ) {
48 $jobOptions[$classOption] = $options[$cmdOption];
49 }
50 }
51 return new self( $jobOptions );
52 }
53
54 function __construct( $options ) {
55 foreach ( $options as $name => $value ) {
56 $this->$name = $value;
57 }
58 $this->store = new ExternalStoreDB;
59 if ( !$this->isChild ) {
60 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
61 } elseif ( $this->slaveId !== false ) {
62 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
63 }
64 $this->useDiff = function_exists( 'xdiff_string_bdiff' );
65 $this->pageBlobClass = $this->useDiff ? 'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
66 $this->orphanBlobClass = 'ConcatenatedGzipHistoryBlob';
67 }
68
69 function debug( $msg ) {
70 wfDebug( "$msg\n" );
71 }
72
73 /**
74 * Wait until the selected slave has caught up to the master.
75 * This allows us to use the slave for things that were committed in a
76 * previous part of this batch process.
77 */
78 function syncDBs() {
79 $dbw = wfGetDB( DB_MASTER );
80 $dbr = wfGetDB( DB_SLAVE );
81 $pos = $dbw->getMasterPos();
82 $dbr->masterPosWait( $pos, 100000 );
83 }
84
85 /**
86 * Execute parent or child depending on the isChild option
87 */
88 function execute() {
89 if ( $this->isChild ) {
90 $this->executeChild();
91 } else {
92 $this->executeParent();
93 }
94 }
95
96 /**
97 * Execute the parent process
98 */
99 function executeParent() {
100 if ( !$this->checkTrackingTable() ) {
101 return;
102 }
103
104 $this->syncDBs();
105 $this->startSlaveProcs();
106 $this->doAllPages();
107 $this->doAllOrphans();
108 $this->killSlaveProcs();
109 }
110
111 /**
112 * Make sure the tracking table exists and isn't empty
113 */
114 function checkTrackingTable() {
115 $dbr = wfGetDB( DB_SLAVE );
116 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
117 echo "Error: blob_tracking table does not exist\n";
118 return false;
119 }
120 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__ );
121 if ( !$row ) {
122 echo "Warning: blob_tracking table contains no rows, skipping this wiki.\n";
123 return false;
124 }
125 return true;
126 }
127
128 /**
129 * Start the worker processes.
130 * These processes will listen on stdin for commands.
131 * This necessary because text recompression is slow: loading, compressing and
132 * writing are all slow.
133 */
134 function startSlaveProcs() {
135 $cmd = 'php ' . wfEscapeShellArg( __FILE__ );
136 foreach ( self::$cmdLineOptionMap as $cmdOption => $classOption ) {
137 if ( in_array( $cmdOption, self::$optionsWithArgs ) ) {
138 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
139 } elseif ( $this->$classOption ) {
140 $cmd .= " --$cmdOption";
141 }
142 }
143 $cmd .= ' --child' .
144 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
145 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters );
146
147 $this->slavePipes = $this->slaveProcs = array();
148 for ( $i = 0; $i < $this->numProcs; $i++ ) {
149 $pipes = false;
150 $spec = array(
151 array( 'pipe', 'r' ),
152 array( 'file', '/dev/stdout', 'w' ),
153 array( 'file', '/dev/stderr', 'w' )
154 );
155 wfSuppressWarnings();
156 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
157 wfRestoreWarnings();
158 if ( !$proc ) {
159 echo "Error opening slave process\n";
160 exit( 1 );
161 }
162 $this->slaveProcs[$i] = $proc;
163 $this->slavePipes[$i] = $pipes[0];
164 }
165 $this->prevSlaveId = -1;
166 }
167
168 /**
169 * Gracefully terminate the child processes
170 */
171 function killSlaveProcs() {
172 for ( $i = 0; $i < $this->numProcs; $i++ ) {
173 $this->dispatchToSlave( $i, 'quit' );
174 }
175 for ( $i = 0; $i < $this->numProcs; $i++ ) {
176 proc_close( $this->slaveProcs[$i] );
177 }
178 }
179
180 /**
181 * Dispatch a command to the next available slave.
182 * This may block until a slave finishes its work and becomes available.
183 */
184 function dispatch( /*...*/ ) {
185 $args = func_get_args();
186 $pipes = $this->slavePipes;
187 $numPipes = stream_select( $x=array(), $pipes, $y=array(), 3600 );
188 if ( !$numPipes ) {
189 echo "Error waiting to write to slaves. Aborting\n";
190 exit( 1 );
191 }
192 for ( $i = 0; $i < $this->numProcs; $i++ ) {
193 $slaveId = ( $i + $this->prevSlaveId + 1 ) % $this->numProcs;
194 if ( isset( $pipes[$slaveId] ) ) {
195 $this->prevSlaveId = $slaveId;
196 $this->dispatchToSlave( $slaveId, $args );
197 return;
198 }
199 }
200 echo "Unreachable\n";
201 exit( 1 );
202 }
203
204 /**
205 * Dispatch a command to a specified slave
206 */
207 function dispatchToSlave( $slaveId, $args ) {
208 $args = (array)$args;
209 $cmd = implode( ' ', $args );
210 fwrite( $this->slavePipes[$slaveId], "$cmd\n" );
211 }
212
213 /**
214 * Move all tracked pages to the new clusters
215 */
216 function doAllPages() {
217 $dbr = wfGetDB( DB_SLAVE );
218 $startId = 0;
219 $endId = $dbr->selectField( 'blob_tracking', 'MAX(bt_page)',
220 # A condition is required so that this query uses the index
221 array( 'bt_moved' => 0 ),
222 __METHOD__ );
223 echo "Moving pages...\n";
224 while ( true ) {
225 $res = $dbr->select( 'blob_tracking',
226 array( 'bt_page' ),
227 array(
228 'bt_moved' => 0,
229 'bt_page > ' . $dbr->addQuotes( $startId )
230 ),
231 __METHOD__,
232 array(
233 'DISTINCT',
234 'ORDER BY' => 'bt_page',
235 'LIMIT' => $this->batchSize,
236 )
237 );
238 if ( !$res->numRows() ) {
239 break;
240 }
241 foreach ( $res as $row ) {
242 $this->dispatch( 'doPage', $row->bt_page );
243 }
244 $startId = $row->bt_page;
245 $this->report( $startId, $endId );
246 }
247 echo "Done moving pages.\n";
248 }
249
250 /**
251 * Display a progress report
252 */
253 function report( $start, $end ) {
254 $this->numBatches++;
255 if ( $this->numBatches >= $this->reportingInterval ) {
256 $this->numBatches = 0;
257 echo "$start / $end\n";
258 wfWaitForSlaves( 5 );
259 }
260 }
261
262 /**
263 * Move all orphan text to the new clusters
264 */
265 function doAllOrphans() {
266 $dbr = wfGetDB( DB_SLAVE );
267 $startId = 0;
268 $endId = $dbr->selectField( 'blob_tracking', 'MAX(bt_text_id)',
269 array( 'bt_moved' => 0, 'bt_page' => 0 ),
270 __METHOD__ );
271 if ( !$endId ) {
272 return;
273 }
274 echo "Moving orphans...\n";
275
276 while ( true ) {
277 $res = $dbr->select( 'blob_tracking',
278 array( 'bt_text_id' ),
279 array(
280 'bt_moved' => 0,
281 'bt_page' => 0,
282 'bt_text_id > ' . $dbr->addQuotes( $startId )
283 ),
284 __METHOD__,
285 array(
286 'DISTINCT',
287 'ORDER BY' => 'bt_text_id',
288 'LIMIT' => $this->batchSize
289 )
290 );
291 if ( !$res->numRows() ) {
292 break;
293 }
294 $args = array( 'doOrphanList' );
295 foreach ( $res as $row ) {
296 $args[] = $row->bt_text_id;
297 }
298 call_user_func_array( array( $this, 'dispatch' ), $args );
299 $startId = $row->bt_text_id;
300 $this->report( $startId, $endId );
301 }
302 echo "Done moving orphans.\n";
303 }
304
305 /**
306 * Main entry point for worker processes
307 */
308 function executeChild() {
309 $this->debug( 'starting' );
310 $this->syncDBs();
311
312 while ( !feof( STDIN ) ) {
313 $line = rtrim( fgets( STDIN ) );
314 if ( $line == '' ) {
315 continue;
316 }
317 $this->debug( $line );
318 $args = explode( ' ', $line );
319 $cmd = array_shift( $args );
320 switch ( $cmd ) {
321 case 'doPage':
322 $this->doPage( intval( $args[0] ) );
323 break;
324 case 'doOrphanList':
325 $this->doOrphanList( array_map( 'intval', $args ) );
326 break;
327 case 'quit':
328 return;
329 }
330 }
331 }
332
333 /**
334 * Move tracked text in a given page
335 */
336 function doPage( $pageId ) {
337 $title = Title::newFromId( $pageId );
338 if ( $title ) {
339 $titleText = $title->getPrefixedText();
340 } else {
341 $titleText = '[deleted]';
342 }
343 $dbr = wfGetDB( DB_SLAVE );
344
345 // Finish any incomplete transactions
346 if ( !$this->copyOnly ) {
347 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
348 }
349
350 $startId = 0;
351 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
352
353 while ( true ) {
354 $res = $dbr->select(
355 array( 'blob_tracking', 'text' ),
356 '*',
357 array(
358 'bt_page' => $pageId,
359 'bt_text_id > ' . $dbr->addQuotes( $startId ),
360 'bt_moved' => 0,
361 'bt_new_url IS NULL',
362 'bt_text_id=old_id',
363 ),
364 __METHOD__,
365 array(
366 'ORDER BY' => 'bt_text_id',
367 'LIMIT' => $this->batchSize
368 )
369 );
370 if ( !$res->numRows() ) {
371 break;
372 }
373
374 $lastTextId = 0;
375 foreach ( $res as $row ) {
376 if ( $lastTextId == $row->bt_text_id ) {
377 // Duplicate (null edit)
378 continue;
379 }
380 $lastTextId = $row->bt_text_id;
381 // Load the text
382 $text = Revision::getRevisionText( $row );
383 if ( $text === false ) {
384 echo "Error loading {$row->bt_rev_id}/{$row->bt_text_id}\n";
385 continue;
386 }
387
388 // Queue it
389 if ( !$trx->addItem( $text, $row->bt_text_id ) ) {
390 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
391 $trx->commit();
392 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
393 }
394 }
395 $startId = $row->bt_text_id;
396 }
397
398 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
399 $trx->commit();
400 }
401
402 /**
403 * Atomic move operation.
404 *
405 * Write the new URL to the text table and set the bt_moved flag.
406 *
407 * This is done in a single transaction to provide restartable behaviour
408 * without data loss.
409 *
410 * The transaction is kept short to reduce locking.
411 */
412 function moveTextRow( $textId, $url ) {
413 $dbw = wfGetDB( DB_MASTER );
414 $dbw->begin();
415 $dbw->update( 'text',
416 array( // set
417 'old_text' => $url,
418 'old_flags' => 'external,utf8',
419 ),
420 array( // where
421 'old_id' => $textId
422 ),
423 __METHOD__
424 );
425 $dbw->update( 'blob_tracking',
426 array( 'bt_moved' => 1 ),
427 array( 'bt_text_id' => $textId ),
428 __METHOD__
429 );
430 $dbw->commit();
431 }
432
433 /**
434 * Moves are done in two phases: bt_new_url and then bt_moved.
435 * - bt_new_url indicates that the text has been copied to the new cluster.
436 * - bt_moved indicates that the text table has been updated.
437 *
438 * This function completes any moves that only have done bt_new_url. This
439 * can happen when the script is interrupted, or when --copy-only is used.
440 */
441 function finishIncompleteMoves( $conds ) {
442 $dbr = wfGetDB( DB_SLAVE );
443
444 $startId = 0;
445 $conds = array_merge( $conds, array(
446 'bt_moved' => 0,
447 'bt_new_url IS NOT NULL'
448 ));
449 while ( true ) {
450 $res = $dbr->select( 'blob_tracking',
451 '*',
452 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
453 __METHOD__,
454 array(
455 'ORDER BY' => 'bt_text_id',
456 'LIMIT' => $this->batchSize,
457 )
458 );
459 if ( !$res->numRows() ) {
460 break;
461 }
462 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
463 foreach ( $res as $row ) {
464 $this->moveTextRow( $row->bt_text_id, $row->bt_new_url );
465 }
466 $startId = $row->bt_text_id;
467 }
468 }
469
470 /**
471 * Returns the name of the next target cluster
472 */
473 function getTargetCluster() {
474 $cluster = next( $this->destClusters );
475 if ( $cluster === false ) {
476 $cluster = reset( $this->destClusters );
477 }
478 return $cluster;
479 }
480
481 /**
482 * Gets a DB master connection for the given external cluster name
483 */
484 function getExtDB( $cluster ) {
485 $lb = wfGetLBFactory()->getExternalLB( $cluster );
486 return $lb->getConnection( DB_MASTER );
487 }
488
489 /**
490 * Move an orphan text_id to the new cluster
491 */
492 function doOrphanList( $textIds ) {
493 // Finish incomplete moves
494 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
495
496 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
497 foreach ( $textIds as $textId ) {
498 $row = wfGetDB( DB_SLAVE )->selectRow( 'text', array( 'old_text', 'old_flags' ),
499 array( 'old_id' => $textId ), __METHOD__ );
500 $text = Revision::getRevisionText( $row );
501 if ( $text === false ) {
502 echo "Error: cannot load revision text for $textId\n";
503 continue;
504 }
505
506 if ( !$trx->addItem( $text, $textId ) ) {
507 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
508 $trx->commit();
509 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
510 }
511 }
512 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
513 $trx->commit();
514 }
515 }
516
517 /**
518 * Class to represent a recompression operation for a single CGZ blob
519 */
520 class CgzCopyTransaction {
521 var $parent;
522 var $blobClass;
523 var $cgz;
524 var $referrers;
525
526 /**
527 * Create a transaction from a RecompressTracked object
528 */
529 function __construct( $parent, $blobClass ) {
530 $this->blobClass = $blobClass;
531 $this->cgz = false;
532 $this->texts = array();
533 $this->parent = $parent;
534 }
535
536 /**
537 * Add text.
538 * Returns false if it's ready to commit.
539 */
540 function addItem( $text, $textId ) {
541 if ( !$this->cgz ) {
542 $class = $this->blobClass;
543 $this->cgz = new $class;
544 }
545 $hash = $this->cgz->addItem( $text );
546 $this->referrers[$textId] = $hash;
547 $this->texts[$textId] = $text;
548 return $this->cgz->isHappy();
549 }
550
551 function getSize() {
552 return count( $this->texts );
553 }
554
555 /**
556 * Recompress text after some aberrant modification
557 */
558 function recompress() {
559 $class = $this->blobClass;
560 $this->cgz = new $class;
561 $this->referrers = array();
562 foreach ( $this->texts as $textId => $text ) {
563 $hash = $this->cgz->addItem( $text );
564 $this->referrers[$textId] = $hash;
565 }
566 }
567
568 /**
569 * Commit the blob.
570 * Does nothing if no text items have been added.
571 * May skip the move if --copy-only is set.
572 */
573 function commit() {
574 $originalCount = count( $this->texts );
575 if ( !$originalCount ) {
576 return;
577 }
578
579 // Check to see if the target text_ids have been moved already.
580 //
581 // We originally read from the slave, so this can happen when a single
582 // text_id is shared between multiple pages. It's rare, but possible
583 // if a delete/move/undelete cycle splits up a null edit.
584 //
585 // We do a locking read to prevent closer-run race conditions.
586 $dbw = wfGetDB( DB_MASTER );
587 $dbw->begin();
588 $res = $dbw->select( 'blob_tracking',
589 array( 'bt_text_id', 'bt_moved' ),
590 array( 'bt_text_id' => array_keys( $this->referrers ) ),
591 __METHOD__, array( 'FOR UPDATE' ) );
592 $dirty = false;
593 foreach ( $res as $row ) {
594 if ( $row->bt_moved ) {
595 # This row has already been moved, remove it
596 $this->parent->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
597 unset( $this->texts[$row->bt_text_id] );
598 $dirty = true;
599 }
600 }
601
602 // Recompress the blob if necessary
603 if ( $dirty ) {
604 if ( !count( $this->texts ) ) {
605 // All have been moved already
606 if ( $originalCount > 1 ) {
607 // This is suspcious, make noise
608 echo "Warning: concurrent operation detected, are there two conflicting " .
609 "processes running, doing the same job?\n";
610 }
611 return;
612 }
613 $this->recompress();
614 }
615
616 // Insert the data into the destination cluster
617 $targetCluster = $this->parent->getTargetCluster();
618 $store = $this->parent->store;
619 $targetDB = $store->getMaster( $targetCluster );
620 $targetDB->clearFlag( DBO_TRX ); // we manage the transactions
621 $targetDB->begin();
622 $baseUrl = $this->parent->store->store( $targetCluster, serialize( $this->cgz ) );
623
624 // Write the new URLs to the blob_tracking table
625 foreach ( $this->referrers as $textId => $hash ) {
626 $url = $baseUrl . '/' . $hash;
627 $dbw->update( 'blob_tracking',
628 array( 'bt_new_url' => $url ),
629 array(
630 'bt_text_id' => $textId,
631 'bt_moved' => 0, # Check for concurrent conflicting update
632 ),
633 __METHOD__
634 );
635 }
636
637 $targetDB->commit();
638 // Critical section here: interruption at this point causes blob duplication
639 // Reversing the order of the commits would cause data loss instead
640 $dbw->commit();
641
642 // Write the new URLs to the text table and set the moved flag
643 if ( !$this->parent->copyOnly ) {
644 foreach ( $this->referrers as $textId => $hash ) {
645 $url = $baseUrl . '/' . $hash;
646 $this->parent->moveTextRow( $textId, $url );
647 }
648 }
649 }
650 }
651