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