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