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