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