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