Merge "Remove maintenance script fixSlaveDesync.php"
[lhc/web/wiklou.git] / maintenance / storage / recompressTracked.php
1 <?php
2 /**
3 * Moves blobs indexed by trackBlobs.php to a specified list of destination
4 * clusters, and recompresses them in the process.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Maintenance ExternalStorage
23 */
24
25 use MediaWiki\Logger\LegacyLogger;
26
27 $optionsWithArgs = RecompressTracked::getOptionsWithArgs();
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
46 $job = RecompressTracked::newFromCommandLine( $args, $options );
47 $job->execute();
48
49 /**
50 * Maintenance script that moves blobs indexed by trackBlobs.php to a specified
51 * list of destination clusters, and recompresses them in the process.
52 *
53 * @ingroup Maintenance ExternalStorage
54 */
55 class RecompressTracked {
56 public $destClusters;
57 public $batchSize = 1000;
58 public $orphanBatchSize = 1000;
59 public $reportingInterval = 10;
60 public $numProcs = 1;
61 public $useDiff, $pageBlobClass, $orphanBlobClass;
62 public $slavePipes, $slaveProcs, $prevSlaveId;
63 public $copyOnly = false;
64 public $isChild = false;
65 public $slaveId = false;
66 public $noCount = false;
67 public $debugLog, $infoLog, $criticalLog;
68 public $store;
69
70 private static $optionsWithArgs = array(
71 'procs',
72 'slave-id',
73 'debug-log',
74 'info-log',
75 'critical-log'
76 );
77
78 private static $cmdLineOptionMap = array(
79 'no-count' => 'noCount',
80 'procs' => 'numProcs',
81 'copy-only' => 'copyOnly',
82 'child' => 'isChild',
83 'slave-id' => 'slaveId',
84 'debug-log' => 'debugLog',
85 'info-log' => 'infoLog',
86 'critical-log' => 'criticalLog',
87 );
88
89 static function getOptionsWithArgs() {
90 return self::$optionsWithArgs;
91 }
92
93 static function newFromCommandLine( $args, $options ) {
94 $jobOptions = array( 'destClusters' => $args );
95 foreach ( self::$cmdLineOptionMap as $cmdOption => $classOption ) {
96 if ( isset( $options[$cmdOption] ) ) {
97 $jobOptions[$classOption] = $options[$cmdOption];
98 }
99 }
100
101 return new self( $jobOptions );
102 }
103
104 function __construct( $options ) {
105 foreach ( $options as $name => $value ) {
106 $this->$name = $value;
107 }
108 $this->store = new ExternalStoreDB;
109 if ( !$this->isChild ) {
110 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
111 } elseif ( $this->slaveId !== false ) {
112 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
113 }
114 $this->useDiff = function_exists( 'xdiff_string_bdiff' );
115 $this->pageBlobClass = $this->useDiff ? 'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
116 $this->orphanBlobClass = 'ConcatenatedGzipHistoryBlob';
117 }
118
119 function debug( $msg ) {
120 wfDebug( "$msg\n" );
121 if ( $this->debugLog ) {
122 $this->logToFile( $msg, $this->debugLog );
123 }
124 }
125
126 function info( $msg ) {
127 echo "$msg\n";
128 if ( $this->infoLog ) {
129 $this->logToFile( $msg, $this->infoLog );
130 }
131 }
132
133 function critical( $msg ) {
134 echo "$msg\n";
135 if ( $this->criticalLog ) {
136 $this->logToFile( $msg, $this->criticalLog );
137 }
138 }
139
140 function logToFile( $msg, $file ) {
141 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
142 if ( $this->slaveId !== false ) {
143 $header .= "({$this->slaveId})";
144 }
145 $header .= ' ' . wfWikiID();
146 LegacyLogger::emit( sprintf( "%-50s %s\n", $header, $msg ), $file );
147 }
148
149 /**
150 * Wait until the selected slave has caught up to the master.
151 * This allows us to use the slave for things that were committed in a
152 * previous part of this batch process.
153 */
154 function syncDBs() {
155 $dbw = wfGetDB( DB_MASTER );
156 $dbr = wfGetDB( DB_SLAVE );
157 $pos = $dbw->getMasterPos();
158 $dbr->masterPosWait( $pos, 100000 );
159 }
160
161 /**
162 * Execute parent or child depending on the isChild option
163 */
164 function execute() {
165 if ( $this->isChild ) {
166 $this->executeChild();
167 } else {
168 $this->executeParent();
169 }
170 }
171
172 /**
173 * Execute the parent process
174 */
175 function executeParent() {
176 if ( !$this->checkTrackingTable() ) {
177 return;
178 }
179
180 $this->syncDBs();
181 $this->startSlaveProcs();
182 $this->doAllPages();
183 $this->doAllOrphans();
184 $this->killSlaveProcs();
185 }
186
187 /**
188 * Make sure the tracking table exists and isn't empty
189 * @return bool
190 */
191 function checkTrackingTable() {
192 $dbr = wfGetDB( DB_SLAVE );
193 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
194 $this->critical( "Error: blob_tracking table does not exist" );
195
196 return false;
197 }
198 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__ );
199 if ( !$row ) {
200 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
201
202 return false;
203 }
204
205 return true;
206 }
207
208 /**
209 * Start the worker processes.
210 * These processes will listen on stdin for commands.
211 * This necessary because text recompression is slow: loading, compressing and
212 * writing are all slow.
213 */
214 function startSlaveProcs() {
215 $cmd = 'php ' . wfEscapeShellArg( __FILE__ );
216 foreach ( self::$cmdLineOptionMap as $cmdOption => $classOption ) {
217 if ( $cmdOption == 'slave-id' ) {
218 continue;
219 } elseif ( in_array( $cmdOption, self::$optionsWithArgs ) && isset( $this->$classOption ) ) {
220 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
221 } elseif ( $this->$classOption ) {
222 $cmd .= " --$cmdOption";
223 }
224 }
225 $cmd .= ' --child' .
226 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
227 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters );
228
229 $this->slavePipes = $this->slaveProcs = array();
230 for ( $i = 0; $i < $this->numProcs; $i++ ) {
231 $pipes = false;
232 $spec = array(
233 array( 'pipe', 'r' ),
234 array( 'file', 'php://stdout', 'w' ),
235 array( 'file', 'php://stderr', 'w' )
236 );
237 MediaWiki\suppressWarnings();
238 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
239 MediaWiki\restoreWarnings();
240 if ( !$proc ) {
241 $this->critical( "Error opening slave process: $cmd" );
242 exit( 1 );
243 }
244 $this->slaveProcs[$i] = $proc;
245 $this->slavePipes[$i] = $pipes[0];
246 }
247 $this->prevSlaveId = -1;
248 }
249
250 /**
251 * Gracefully terminate the child processes
252 */
253 function killSlaveProcs() {
254 $this->info( "Waiting for slave processes to finish..." );
255 for ( $i = 0; $i < $this->numProcs; $i++ ) {
256 $this->dispatchToSlave( $i, 'quit' );
257 }
258 for ( $i = 0; $i < $this->numProcs; $i++ ) {
259 $status = proc_close( $this->slaveProcs[$i] );
260 if ( $status ) {
261 $this->critical( "Warning: child #$i exited with status $status" );
262 }
263 }
264 $this->info( "Done." );
265 }
266
267 /**
268 * Dispatch a command to the next available slave.
269 * This may block until a slave finishes its work and becomes available.
270 */
271 function dispatch( /*...*/ ) {
272 $args = func_get_args();
273 $pipes = $this->slavePipes;
274 $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
275 if ( !$numPipes ) {
276 $this->critical( "Error waiting to write to slaves. Aborting" );
277 exit( 1 );
278 }
279 for ( $i = 0; $i < $this->numProcs; $i++ ) {
280 $slaveId = ( $i + $this->prevSlaveId + 1 ) % $this->numProcs;
281 if ( isset( $pipes[$slaveId] ) ) {
282 $this->prevSlaveId = $slaveId;
283 $this->dispatchToSlave( $slaveId, $args );
284
285 return;
286 }
287 }
288 $this->critical( "Unreachable" );
289 exit( 1 );
290 }
291
292 /**
293 * Dispatch a command to a specified slave
294 * @param int $slaveId
295 * @param array|string $args
296 */
297 function dispatchToSlave( $slaveId, $args ) {
298 $args = (array)$args;
299 $cmd = implode( ' ', $args );
300 fwrite( $this->slavePipes[$slaveId], "$cmd\n" );
301 }
302
303 /**
304 * Move all tracked pages to the new clusters
305 */
306 function doAllPages() {
307 $dbr = wfGetDB( DB_SLAVE );
308 $i = 0;
309 $startId = 0;
310 if ( $this->noCount ) {
311 $numPages = '[unknown]';
312 } else {
313 $numPages = $dbr->selectField( 'blob_tracking',
314 'COUNT(DISTINCT bt_page)',
315 # A condition is required so that this query uses the index
316 array( 'bt_moved' => 0 ),
317 __METHOD__
318 );
319 }
320 if ( $this->copyOnly ) {
321 $this->info( "Copying pages..." );
322 } else {
323 $this->info( "Moving pages..." );
324 }
325 while ( true ) {
326 $res = $dbr->select( 'blob_tracking',
327 array( 'bt_page' ),
328 array(
329 'bt_moved' => 0,
330 'bt_page > ' . $dbr->addQuotes( $startId )
331 ),
332 __METHOD__,
333 array(
334 'DISTINCT',
335 'ORDER BY' => 'bt_page',
336 'LIMIT' => $this->batchSize,
337 )
338 );
339 if ( !$res->numRows() ) {
340 break;
341 }
342 foreach ( $res as $row ) {
343 $this->dispatch( 'doPage', $row->bt_page );
344 $i++;
345 }
346 $startId = $row->bt_page;
347 $this->report( 'pages', $i, $numPages );
348 }
349 $this->report( 'pages', $i, $numPages );
350 if ( $this->copyOnly ) {
351 $this->info( "All page copies queued." );
352 } else {
353 $this->info( "All page moves queued." );
354 }
355 }
356
357 /**
358 * Display a progress report
359 * @param string $label
360 * @param int $current
361 * @param int $end
362 */
363 function report( $label, $current, $end ) {
364 $this->numBatches++;
365 if ( $current == $end || $this->numBatches >= $this->reportingInterval ) {
366 $this->numBatches = 0;
367 $this->info( "$label: $current / $end" );
368 $this->waitForSlaves();
369 }
370 }
371
372 /**
373 * Move all orphan text to the new clusters
374 */
375 function doAllOrphans() {
376 $dbr = wfGetDB( DB_SLAVE );
377 $startId = 0;
378 $i = 0;
379 if ( $this->noCount ) {
380 $numOrphans = '[unknown]';
381 } else {
382 $numOrphans = $dbr->selectField( 'blob_tracking',
383 'COUNT(DISTINCT bt_text_id)',
384 array( 'bt_moved' => 0, 'bt_page' => 0 ),
385 __METHOD__ );
386 if ( !$numOrphans ) {
387 return;
388 }
389 }
390 if ( $this->copyOnly ) {
391 $this->info( "Copying orphans..." );
392 } else {
393 $this->info( "Moving orphans..." );
394 }
395
396 while ( true ) {
397 $res = $dbr->select( 'blob_tracking',
398 array( 'bt_text_id' ),
399 array(
400 'bt_moved' => 0,
401 'bt_page' => 0,
402 'bt_text_id > ' . $dbr->addQuotes( $startId )
403 ),
404 __METHOD__,
405 array(
406 'DISTINCT',
407 'ORDER BY' => 'bt_text_id',
408 'LIMIT' => $this->batchSize
409 )
410 );
411 if ( !$res->numRows() ) {
412 break;
413 }
414 $ids = array();
415 foreach ( $res as $row ) {
416 $ids[] = $row->bt_text_id;
417 $i++;
418 }
419 // Need to send enough orphan IDs to the child at a time to fill a blob,
420 // so orphanBatchSize needs to be at least ~100.
421 // batchSize can be smaller or larger.
422 while ( count( $ids ) > $this->orphanBatchSize ) {
423 $args = array_slice( $ids, 0, $this->orphanBatchSize );
424 $ids = array_slice( $ids, $this->orphanBatchSize );
425 array_unshift( $args, 'doOrphanList' );
426 call_user_func_array( array( $this, 'dispatch' ), $args );
427 }
428 if ( count( $ids ) ) {
429 $args = $ids;
430 array_unshift( $args, 'doOrphanList' );
431 call_user_func_array( array( $this, 'dispatch' ), $args );
432 }
433
434 $startId = $row->bt_text_id;
435 $this->report( 'orphans', $i, $numOrphans );
436 }
437 $this->report( 'orphans', $i, $numOrphans );
438 $this->info( "All orphans queued." );
439 }
440
441 /**
442 * Main entry point for worker processes
443 */
444 function executeChild() {
445 $this->debug( 'starting' );
446 $this->syncDBs();
447
448 while ( !feof( STDIN ) ) {
449 $line = rtrim( fgets( STDIN ) );
450 if ( $line == '' ) {
451 continue;
452 }
453 $this->debug( $line );
454 $args = explode( ' ', $line );
455 $cmd = array_shift( $args );
456 switch ( $cmd ) {
457 case 'doPage':
458 $this->doPage( intval( $args[0] ) );
459 break;
460 case 'doOrphanList':
461 $this->doOrphanList( array_map( 'intval', $args ) );
462 break;
463 case 'quit':
464 return;
465 }
466 $this->waitForSlaves();
467 }
468 }
469
470 /**
471 * Move tracked text in a given page
472 *
473 * @param int $pageId
474 */
475 function doPage( $pageId ) {
476 $title = Title::newFromID( $pageId );
477 if ( $title ) {
478 $titleText = $title->getPrefixedText();
479 } else {
480 $titleText = '[deleted]';
481 }
482 $dbr = wfGetDB( DB_SLAVE );
483
484 // Finish any incomplete transactions
485 if ( !$this->copyOnly ) {
486 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
487 $this->syncDBs();
488 }
489
490 $startId = 0;
491 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
492
493 while ( true ) {
494 $res = $dbr->select(
495 array( 'blob_tracking', 'text' ),
496 '*',
497 array(
498 'bt_page' => $pageId,
499 'bt_text_id > ' . $dbr->addQuotes( $startId ),
500 'bt_moved' => 0,
501 'bt_new_url IS NULL',
502 'bt_text_id=old_id',
503 ),
504 __METHOD__,
505 array(
506 'ORDER BY' => 'bt_text_id',
507 'LIMIT' => $this->batchSize
508 )
509 );
510 if ( !$res->numRows() ) {
511 break;
512 }
513
514 $lastTextId = 0;
515 foreach ( $res as $row ) {
516 if ( $lastTextId == $row->bt_text_id ) {
517 // Duplicate (null edit)
518 continue;
519 }
520 $lastTextId = $row->bt_text_id;
521 // Load the text
522 $text = Revision::getRevisionText( $row );
523 if ( $text === false ) {
524 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
525 continue;
526 }
527
528 // Queue it
529 if ( !$trx->addItem( $text, $row->bt_text_id ) ) {
530 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
531 $trx->commit();
532 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
533 $this->waitForSlaves();
534 }
535 }
536 $startId = $row->bt_text_id;
537 }
538
539 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
540 $trx->commit();
541 }
542
543 /**
544 * Atomic move operation.
545 *
546 * Write the new URL to the text table and set the bt_moved flag.
547 *
548 * This is done in a single transaction to provide restartable behavior
549 * without data loss.
550 *
551 * The transaction is kept short to reduce locking.
552 *
553 * @param int $textId
554 * @param string $url
555 */
556 function moveTextRow( $textId, $url ) {
557 if ( $this->copyOnly ) {
558 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
559 exit( 1 );
560 }
561 $dbw = wfGetDB( DB_MASTER );
562 $dbw->begin( __METHOD__ );
563 $dbw->update( 'text',
564 array( // set
565 'old_text' => $url,
566 'old_flags' => 'external,utf-8',
567 ),
568 array( // where
569 'old_id' => $textId
570 ),
571 __METHOD__
572 );
573 $dbw->update( 'blob_tracking',
574 array( 'bt_moved' => 1 ),
575 array( 'bt_text_id' => $textId ),
576 __METHOD__
577 );
578 $dbw->commit( __METHOD__ );
579 }
580
581 /**
582 * Moves are done in two phases: bt_new_url and then bt_moved.
583 * - bt_new_url indicates that the text has been copied to the new cluster.
584 * - bt_moved indicates that the text table has been updated.
585 *
586 * This function completes any moves that only have done bt_new_url. This
587 * can happen when the script is interrupted, or when --copy-only is used.
588 *
589 * @param array $conds
590 */
591 function finishIncompleteMoves( $conds ) {
592 $dbr = wfGetDB( DB_SLAVE );
593
594 $startId = 0;
595 $conds = array_merge( $conds, array(
596 'bt_moved' => 0,
597 'bt_new_url IS NOT NULL'
598 ) );
599 while ( true ) {
600 $res = $dbr->select( 'blob_tracking',
601 '*',
602 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
603 __METHOD__,
604 array(
605 'ORDER BY' => 'bt_text_id',
606 'LIMIT' => $this->batchSize,
607 )
608 );
609 if ( !$res->numRows() ) {
610 break;
611 }
612 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
613 foreach ( $res as $row ) {
614 $this->moveTextRow( $row->bt_text_id, $row->bt_new_url );
615 if ( $row->bt_text_id % 10 == 0 ) {
616 $this->waitForSlaves();
617 }
618 }
619 $startId = $row->bt_text_id;
620 }
621 }
622
623 /**
624 * Returns the name of the next target cluster
625 * @return string
626 */
627 function getTargetCluster() {
628 $cluster = next( $this->destClusters );
629 if ( $cluster === false ) {
630 $cluster = reset( $this->destClusters );
631 }
632
633 return $cluster;
634 }
635
636 /**
637 * Gets a DB master connection for the given external cluster name
638 * @param string $cluster
639 * @return DatabaseBase
640 */
641 function getExtDB( $cluster ) {
642 $lb = wfGetLBFactory()->getExternalLB( $cluster );
643
644 return $lb->getConnection( DB_MASTER );
645 }
646
647 /**
648 * Move an orphan text_id to the new cluster
649 *
650 * @param array $textIds
651 */
652 function doOrphanList( $textIds ) {
653 // Finish incomplete moves
654 if ( !$this->copyOnly ) {
655 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
656 $this->syncDBs();
657 }
658
659 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
660
661 $res = wfGetDB( DB_SLAVE )->select(
662 array( 'text', 'blob_tracking' ),
663 array( 'old_id', 'old_text', 'old_flags' ),
664 array(
665 'old_id' => $textIds,
666 'bt_text_id=old_id',
667 'bt_moved' => 0,
668 ),
669 __METHOD__,
670 array( 'DISTINCT' )
671 );
672
673 foreach ( $res as $row ) {
674 $text = Revision::getRevisionText( $row );
675 if ( $text === false ) {
676 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
677 continue;
678 }
679
680 if ( !$trx->addItem( $text, $row->old_id ) ) {
681 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
682 $trx->commit();
683 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
684 $this->waitForSlaves();
685 }
686 }
687 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
688 $trx->commit();
689 }
690
691 /**
692 * Wait for slaves (quietly)
693 */
694 function waitForSlaves() {
695 $lb = wfGetLB();
696 while ( true ) {
697 list( $host, $maxLag ) = $lb->getMaxLag();
698 if ( $maxLag < 2 ) {
699 break;
700 }
701 sleep( 5 );
702 }
703 }
704 }
705
706 /**
707 * Class to represent a recompression operation for a single CGZ blob
708 */
709 class CgzCopyTransaction {
710 public $parent;
711 public $blobClass;
712 public $cgz;
713 public $referrers;
714
715 /**
716 * Create a transaction from a RecompressTracked object
717 * @param RecompressTracked $parent
718 * @param string $blobClass
719 */
720 function __construct( $parent, $blobClass ) {
721 $this->blobClass = $blobClass;
722 $this->cgz = false;
723 $this->texts = array();
724 $this->parent = $parent;
725 }
726
727 /**
728 * Add text.
729 * Returns false if it's ready to commit.
730 * @param string $text
731 * @param int $textId
732 * @return bool
733 */
734 function addItem( $text, $textId ) {
735 if ( !$this->cgz ) {
736 $class = $this->blobClass;
737 $this->cgz = new $class;
738 }
739 $hash = $this->cgz->addItem( $text );
740 $this->referrers[$textId] = $hash;
741 $this->texts[$textId] = $text;
742
743 return $this->cgz->isHappy();
744 }
745
746 function getSize() {
747 return count( $this->texts );
748 }
749
750 /**
751 * Recompress text after some aberrant modification
752 */
753 function recompress() {
754 $class = $this->blobClass;
755 $this->cgz = new $class;
756 $this->referrers = array();
757 foreach ( $this->texts as $textId => $text ) {
758 $hash = $this->cgz->addItem( $text );
759 $this->referrers[$textId] = $hash;
760 }
761 }
762
763 /**
764 * Commit the blob.
765 * Does nothing if no text items have been added.
766 * May skip the move if --copy-only is set.
767 */
768 function commit() {
769 $originalCount = count( $this->texts );
770 if ( !$originalCount ) {
771 return;
772 }
773
774 // Check to see if the target text_ids have been moved already.
775 //
776 // We originally read from the slave, so this can happen when a single
777 // text_id is shared between multiple pages. It's rare, but possible
778 // if a delete/move/undelete cycle splits up a null edit.
779 //
780 // We do a locking read to prevent closer-run race conditions.
781 $dbw = wfGetDB( DB_MASTER );
782 $dbw->begin( __METHOD__ );
783 $res = $dbw->select( 'blob_tracking',
784 array( 'bt_text_id', 'bt_moved' ),
785 array( 'bt_text_id' => array_keys( $this->referrers ) ),
786 __METHOD__, array( 'FOR UPDATE' ) );
787 $dirty = false;
788 foreach ( $res as $row ) {
789 if ( $row->bt_moved ) {
790 # This row has already been moved, remove it
791 $this->parent->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
792 unset( $this->texts[$row->bt_text_id] );
793 $dirty = true;
794 }
795 }
796
797 // Recompress the blob if necessary
798 if ( $dirty ) {
799 if ( !count( $this->texts ) ) {
800 // All have been moved already
801 if ( $originalCount > 1 ) {
802 // This is suspcious, make noise
803 $this->critical( "Warning: concurrent operation detected, are there two conflicting " .
804 "processes running, doing the same job?" );
805 }
806
807 return;
808 }
809 $this->recompress();
810 }
811
812 // Insert the data into the destination cluster
813 $targetCluster = $this->parent->getTargetCluster();
814 $store = $this->parent->store;
815 $targetDB = $store->getMaster( $targetCluster );
816 $targetDB->clearFlag( DBO_TRX ); // we manage the transactions
817 $targetDB->begin( __METHOD__ );
818 $baseUrl = $this->parent->store->store( $targetCluster, serialize( $this->cgz ) );
819
820 // Write the new URLs to the blob_tracking table
821 foreach ( $this->referrers as $textId => $hash ) {
822 $url = $baseUrl . '/' . $hash;
823 $dbw->update( 'blob_tracking',
824 array( 'bt_new_url' => $url ),
825 array(
826 'bt_text_id' => $textId,
827 'bt_moved' => 0, # Check for concurrent conflicting update
828 ),
829 __METHOD__
830 );
831 }
832
833 $targetDB->commit( __METHOD__ );
834 // Critical section here: interruption at this point causes blob duplication
835 // Reversing the order of the commits would cause data loss instead
836 $dbw->commit( __METHOD__ );
837
838 // Write the new URLs to the text table and set the moved flag
839 if ( !$this->parent->copyOnly ) {
840 foreach ( $this->referrers as $textId => $hash ) {
841 $url = $baseUrl . '/' . $hash;
842 $this->parent->moveTextRow( $textId, $url );
843 }
844 }
845 }
846 }