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