Merge "RELEASE-NOTES-1.32: Re-wrap to 80 chars again"
[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 $numPipes = stream_select( $x = [], $pipes, $y = [], 3600 );
278 if ( !$numPipes ) {
279 $this->critical( "Error waiting to write to replica DBs. Aborting" );
280 exit( 1 );
281 }
282 for ( $i = 0; $i < $this->numProcs; $i++ ) {
283 $replicaId = ( $i + $this->prevReplicaId + 1 ) % $this->numProcs;
284 if ( isset( $pipes[$replicaId] ) ) {
285 $this->prevReplicaId = $replicaId;
286 $this->dispatchToReplica( $replicaId, $args );
287
288 return;
289 }
290 }
291 $this->critical( "Unreachable" );
292 exit( 1 );
293 }
294
295 /**
296 * Dispatch a command to a specified replica DB
297 * @param int $replicaId
298 * @param array|string $args
299 */
300 function dispatchToReplica( $replicaId, $args ) {
301 $args = (array)$args;
302 $cmd = implode( ' ', $args );
303 fwrite( $this->replicaPipes[$replicaId], "$cmd\n" );
304 }
305
306 /**
307 * Move all tracked pages to the new clusters
308 */
309 function doAllPages() {
310 $dbr = wfGetDB( DB_REPLICA );
311 $i = 0;
312 $startId = 0;
313 if ( $this->noCount ) {
314 $numPages = '[unknown]';
315 } else {
316 $numPages = $dbr->selectField( 'blob_tracking',
317 'COUNT(DISTINCT bt_page)',
318 # A condition is required so that this query uses the index
319 [ 'bt_moved' => 0 ],
320 __METHOD__
321 );
322 }
323 if ( $this->copyOnly ) {
324 $this->info( "Copying pages..." );
325 } else {
326 $this->info( "Moving pages..." );
327 }
328 while ( true ) {
329 $res = $dbr->select( 'blob_tracking',
330 [ 'bt_page' ],
331 [
332 'bt_moved' => 0,
333 'bt_page > ' . $dbr->addQuotes( $startId )
334 ],
335 __METHOD__,
336 [
337 'DISTINCT',
338 'ORDER BY' => 'bt_page',
339 'LIMIT' => $this->batchSize,
340 ]
341 );
342 if ( !$res->numRows() ) {
343 break;
344 }
345 foreach ( $res as $row ) {
346 $startId = $row->bt_page;
347 $this->dispatch( 'doPage', $row->bt_page );
348 $i++;
349 }
350 $this->report( 'pages', $i, $numPages );
351 }
352 $this->report( 'pages', $i, $numPages );
353 if ( $this->copyOnly ) {
354 $this->info( "All page copies queued." );
355 } else {
356 $this->info( "All page moves queued." );
357 }
358 }
359
360 /**
361 * Display a progress report
362 * @param string $label
363 * @param int $current
364 * @param int $end
365 */
366 function report( $label, $current, $end ) {
367 $this->numBatches++;
368 if ( $current == $end || $this->numBatches >= $this->reportingInterval ) {
369 $this->numBatches = 0;
370 $this->info( "$label: $current / $end" );
371 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
372 }
373 }
374
375 /**
376 * Move all orphan text to the new clusters
377 */
378 function doAllOrphans() {
379 $dbr = wfGetDB( DB_REPLICA );
380 $startId = 0;
381 $i = 0;
382 if ( $this->noCount ) {
383 $numOrphans = '[unknown]';
384 } else {
385 $numOrphans = $dbr->selectField( 'blob_tracking',
386 'COUNT(DISTINCT bt_text_id)',
387 [ 'bt_moved' => 0, 'bt_page' => 0 ],
388 __METHOD__ );
389 if ( !$numOrphans ) {
390 return;
391 }
392 }
393 if ( $this->copyOnly ) {
394 $this->info( "Copying orphans..." );
395 } else {
396 $this->info( "Moving orphans..." );
397 }
398
399 while ( true ) {
400 $res = $dbr->select( 'blob_tracking',
401 [ 'bt_text_id' ],
402 [
403 'bt_moved' => 0,
404 'bt_page' => 0,
405 'bt_text_id > ' . $dbr->addQuotes( $startId )
406 ],
407 __METHOD__,
408 [
409 'DISTINCT',
410 'ORDER BY' => 'bt_text_id',
411 'LIMIT' => $this->batchSize
412 ]
413 );
414 if ( !$res->numRows() ) {
415 break;
416 }
417 $ids = [];
418 foreach ( $res as $row ) {
419 $startId = $row->bt_text_id;
420 $ids[] = $row->bt_text_id;
421 $i++;
422 }
423 // Need to send enough orphan IDs to the child at a time to fill a blob,
424 // so orphanBatchSize needs to be at least ~100.
425 // batchSize can be smaller or larger.
426 while ( count( $ids ) > $this->orphanBatchSize ) {
427 $args = array_slice( $ids, 0, $this->orphanBatchSize );
428 $ids = array_slice( $ids, $this->orphanBatchSize );
429 array_unshift( $args, 'doOrphanList' );
430 $this->dispatch( ...$args );
431 }
432 if ( count( $ids ) ) {
433 $args = $ids;
434 array_unshift( $args, 'doOrphanList' );
435 $this->dispatch( ...$args );
436 }
437
438 $this->report( 'orphans', $i, $numOrphans );
439 }
440 $this->report( 'orphans', $i, $numOrphans );
441 $this->info( "All orphans queued." );
442 }
443
444 /**
445 * Main entry point for worker processes
446 */
447 function executeChild() {
448 $this->debug( 'starting' );
449 $this->syncDBs();
450
451 while ( !feof( STDIN ) ) {
452 $line = rtrim( fgets( STDIN ) );
453 if ( $line == '' ) {
454 continue;
455 }
456 $this->debug( $line );
457 $args = explode( ' ', $line );
458 $cmd = array_shift( $args );
459 switch ( $cmd ) {
460 case 'doPage':
461 $this->doPage( intval( $args[0] ) );
462 break;
463 case 'doOrphanList':
464 $this->doOrphanList( array_map( 'intval', $args ) );
465 break;
466 case 'quit':
467 return;
468 }
469 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
470 }
471 }
472
473 /**
474 * Move tracked text in a given page
475 *
476 * @param int $pageId
477 */
478 function doPage( $pageId ) {
479 $title = Title::newFromID( $pageId );
480 if ( $title ) {
481 $titleText = $title->getPrefixedText();
482 } else {
483 $titleText = '[deleted]';
484 }
485 $dbr = wfGetDB( DB_REPLICA );
486
487 // Finish any incomplete transactions
488 if ( !$this->copyOnly ) {
489 $this->finishIncompleteMoves( [ 'bt_page' => $pageId ] );
490 $this->syncDBs();
491 }
492
493 $startId = 0;
494 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
495
496 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
497 while ( true ) {
498 $res = $dbr->select(
499 [ 'blob_tracking', 'text' ],
500 '*',
501 [
502 'bt_page' => $pageId,
503 'bt_text_id > ' . $dbr->addQuotes( $startId ),
504 'bt_moved' => 0,
505 'bt_new_url IS NULL',
506 'bt_text_id=old_id',
507 ],
508 __METHOD__,
509 [
510 'ORDER BY' => 'bt_text_id',
511 'LIMIT' => $this->batchSize
512 ]
513 );
514 if ( !$res->numRows() ) {
515 break;
516 }
517
518 $lastTextId = 0;
519 foreach ( $res as $row ) {
520 $startId = $row->bt_text_id;
521 if ( $lastTextId == $row->bt_text_id ) {
522 // Duplicate (null edit)
523 continue;
524 }
525 $lastTextId = $row->bt_text_id;
526 // Load the text
527 $text = Revision::getRevisionText( $row );
528 if ( $text === false ) {
529 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
530 continue;
531 }
532
533 // Queue it
534 if ( !$trx->addItem( $text, $row->bt_text_id ) ) {
535 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
536 $trx->commit();
537 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
538 $lbFactory->waitForReplication();
539 }
540 }
541 }
542
543 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
544 $trx->commit();
545 }
546
547 /**
548 * Atomic move operation.
549 *
550 * Write the new URL to the text table and set the bt_moved flag.
551 *
552 * This is done in a single transaction to provide restartable behavior
553 * without data loss.
554 *
555 * The transaction is kept short to reduce locking.
556 *
557 * @param int $textId
558 * @param string $url
559 */
560 function moveTextRow( $textId, $url ) {
561 if ( $this->copyOnly ) {
562 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
563 exit( 1 );
564 }
565 $dbw = wfGetDB( DB_MASTER );
566 $dbw->begin( __METHOD__ );
567 $dbw->update( 'text',
568 [ // set
569 'old_text' => $url,
570 'old_flags' => 'external,utf-8',
571 ],
572 [ // where
573 'old_id' => $textId
574 ],
575 __METHOD__
576 );
577 $dbw->update( 'blob_tracking',
578 [ 'bt_moved' => 1 ],
579 [ 'bt_text_id' => $textId ],
580 __METHOD__
581 );
582 $dbw->commit( __METHOD__ );
583 }
584
585 /**
586 * Moves are done in two phases: bt_new_url and then bt_moved.
587 * - bt_new_url indicates that the text has been copied to the new cluster.
588 * - bt_moved indicates that the text table has been updated.
589 *
590 * This function completes any moves that only have done bt_new_url. This
591 * can happen when the script is interrupted, or when --copy-only is used.
592 *
593 * @param array $conds
594 */
595 function finishIncompleteMoves( $conds ) {
596 $dbr = wfGetDB( DB_REPLICA );
597 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
598
599 $startId = 0;
600 $conds = array_merge( $conds, [
601 'bt_moved' => 0,
602 'bt_new_url IS NOT NULL'
603 ] );
604 while ( true ) {
605 $res = $dbr->select( 'blob_tracking',
606 '*',
607 array_merge( $conds, [ 'bt_text_id > ' . $dbr->addQuotes( $startId ) ] ),
608 __METHOD__,
609 [
610 'ORDER BY' => 'bt_text_id',
611 'LIMIT' => $this->batchSize,
612 ]
613 );
614 if ( !$res->numRows() ) {
615 break;
616 }
617 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
618 foreach ( $res as $row ) {
619 $startId = $row->bt_text_id;
620 $this->moveTextRow( $row->bt_text_id, $row->bt_new_url );
621 if ( $row->bt_text_id % 10 == 0 ) {
622 $lbFactory->waitForReplication();
623 }
624 }
625 }
626 }
627
628 /**
629 * Returns the name of the next target cluster
630 * @return string
631 */
632 function getTargetCluster() {
633 $cluster = next( $this->destClusters );
634 if ( $cluster === false ) {
635 $cluster = reset( $this->destClusters );
636 }
637
638 return $cluster;
639 }
640
641 /**
642 * Gets a DB master connection for the given external cluster name
643 * @param string $cluster
644 * @return IDatabase
645 */
646 function getExtDB( $cluster ) {
647 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
648 $lb = $lbFactory->getExternalLB( $cluster );
649
650 return $lb->getConnection( DB_MASTER );
651 }
652
653 /**
654 * Move an orphan text_id to the new cluster
655 *
656 * @param array $textIds
657 */
658 function doOrphanList( $textIds ) {
659 // Finish incomplete moves
660 if ( !$this->copyOnly ) {
661 $this->finishIncompleteMoves( [ 'bt_text_id' => $textIds ] );
662 $this->syncDBs();
663 }
664
665 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
666
667 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
668 $res = wfGetDB( DB_REPLICA )->select(
669 [ 'text', 'blob_tracking' ],
670 [ 'old_id', 'old_text', 'old_flags' ],
671 [
672 'old_id' => $textIds,
673 'bt_text_id=old_id',
674 'bt_moved' => 0,
675 ],
676 __METHOD__,
677 [ 'DISTINCT' ]
678 );
679
680 foreach ( $res as $row ) {
681 $text = Revision::getRevisionText( $row );
682 if ( $text === false ) {
683 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
684 continue;
685 }
686
687 if ( !$trx->addItem( $text, $row->old_id ) ) {
688 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
689 $trx->commit();
690 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
691 $lbFactory->waitForReplication();
692 }
693 }
694 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
695 $trx->commit();
696 }
697 }
698
699 /**
700 * Class to represent a recompression operation for a single CGZ blob
701 */
702 class CgzCopyTransaction {
703 /** @var RecompressTracked */
704 public $parent;
705 public $blobClass;
706 /** @var ConcatenatedGzipHistoryBlob */
707 public $cgz;
708 public $referrers;
709
710 /**
711 * Create a transaction from a RecompressTracked object
712 * @param RecompressTracked $parent
713 * @param string $blobClass
714 */
715 function __construct( $parent, $blobClass ) {
716 $this->blobClass = $blobClass;
717 $this->cgz = false;
718 $this->texts = [];
719 $this->parent = $parent;
720 }
721
722 /**
723 * Add text.
724 * Returns false if it's ready to commit.
725 * @param string $text
726 * @param int $textId
727 * @return bool
728 */
729 function addItem( $text, $textId ) {
730 if ( !$this->cgz ) {
731 $class = $this->blobClass;
732 $this->cgz = new $class;
733 }
734 $hash = $this->cgz->addItem( $text );
735 $this->referrers[$textId] = $hash;
736 $this->texts[$textId] = $text;
737
738 return $this->cgz->isHappy();
739 }
740
741 function getSize() {
742 return count( $this->texts );
743 }
744
745 /**
746 * Recompress text after some aberrant modification
747 */
748 function recompress() {
749 $class = $this->blobClass;
750 $this->cgz = new $class;
751 $this->referrers = [];
752 foreach ( $this->texts as $textId => $text ) {
753 $hash = $this->cgz->addItem( $text );
754 $this->referrers[$textId] = $hash;
755 }
756 }
757
758 /**
759 * Commit the blob.
760 * Does nothing if no text items have been added.
761 * May skip the move if --copy-only is set.
762 */
763 function commit() {
764 $originalCount = count( $this->texts );
765 if ( !$originalCount ) {
766 return;
767 }
768
769 /* Check to see if the target text_ids have been moved already.
770 *
771 * We originally read from the replica DB, so this can happen when a single
772 * text_id is shared between multiple pages. It's rare, but possible
773 * if a delete/move/undelete cycle splits up a null edit.
774 *
775 * We do a locking read to prevent closer-run race conditions.
776 */
777 $dbw = wfGetDB( DB_MASTER );
778 $dbw->begin( __METHOD__ );
779 $res = $dbw->select( 'blob_tracking',
780 [ 'bt_text_id', 'bt_moved' ],
781 [ 'bt_text_id' => array_keys( $this->referrers ) ],
782 __METHOD__, [ 'FOR UPDATE' ] );
783 $dirty = false;
784 foreach ( $res as $row ) {
785 if ( $row->bt_moved ) {
786 # This row has already been moved, remove it
787 $this->parent->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
788 unset( $this->texts[$row->bt_text_id] );
789 $dirty = true;
790 }
791 }
792
793 // Recompress the blob if necessary
794 if ( $dirty ) {
795 if ( !count( $this->texts ) ) {
796 // All have been moved already
797 if ( $originalCount > 1 ) {
798 // This is suspcious, make noise
799 $this->parent->critical(
800 "Warning: concurrent operation detected, are there two conflicting " .
801 "processes running, doing the same job?" );
802 }
803
804 return;
805 }
806 $this->recompress();
807 }
808
809 // Insert the data into the destination cluster
810 $targetCluster = $this->parent->getTargetCluster();
811 $store = $this->parent->store;
812 $targetDB = $store->getMaster( $targetCluster );
813 $targetDB->clearFlag( DBO_TRX ); // we manage the transactions
814 $targetDB->begin( __METHOD__ );
815 $baseUrl = $this->parent->store->store( $targetCluster, serialize( $this->cgz ) );
816
817 // Write the new URLs to the blob_tracking table
818 foreach ( $this->referrers as $textId => $hash ) {
819 $url = $baseUrl . '/' . $hash;
820 $dbw->update( 'blob_tracking',
821 [ 'bt_new_url' => $url ],
822 [
823 'bt_text_id' => $textId,
824 'bt_moved' => 0, # Check for concurrent conflicting update
825 ],
826 __METHOD__
827 );
828 }
829
830 $targetDB->commit( __METHOD__ );
831 // Critical section here: interruption at this point causes blob duplication
832 // Reversing the order of the commits would cause data loss instead
833 $dbw->commit( __METHOD__ );
834
835 // Write the new URLs to the text table and set the moved flag
836 if ( !$this->parent->copyOnly ) {
837 foreach ( $this->referrers as $textId => $hash ) {
838 $url = $baseUrl . '/' . $hash;
839 $this->parent->moveTextRow( $textId, $url );
840 }
841 }
842 }
843 }