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