Merge "Optimize HashRing to avoid hashing for the common single-location case"
[lhc/web/wiklou.git] / maintenance / includes / TextPassDumper.php
1 <?php
2 /**
3 * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
4 *
5 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Dump
25 * @ingroup Maintenance
26 */
27
28 require_once __DIR__ . '/BackupDumper.php';
29 require_once __DIR__ . '/SevenZipStream.php';
30 require_once __DIR__ . '/../../includes/export/WikiExporter.php';
31
32 use MediaWiki\MediaWikiServices;
33 use MediaWiki\Shell\Shell;
34 use MediaWiki\Storage\BlobAccessException;
35 use MediaWiki\Storage\SqlBlobStore;
36 use Wikimedia\Rdbms\IMaintainableDatabase;
37
38 /**
39 * @ingroup Maintenance
40 */
41 class TextPassDumper extends BackupDumper {
42 /** @var BaseDump */
43 public $prefetch = null;
44 /** @var string|bool */
45 private $thisPage;
46 /** @var string|bool */
47 private $thisRev;
48
49 // when we spend more than maxTimeAllowed seconds on this run, we continue
50 // processing until we write out the next complete page, then save output file(s),
51 // rename it/them and open new one(s)
52 public $maxTimeAllowed = 0; // 0 = no limit
53
54 protected $input = "php://stdin";
55 protected $history = WikiExporter::FULL;
56 protected $fetchCount = 0;
57 protected $prefetchCount = 0;
58 protected $prefetchCountLast = 0;
59 protected $fetchCountLast = 0;
60
61 protected $maxFailures = 5;
62 protected $maxConsecutiveFailedTextRetrievals = 200;
63 protected $failureTimeout = 5; // Seconds to sleep after db failure
64
65 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
66
67 /** @var array */
68 protected $php = [];
69 protected $spawn = false;
70
71 /**
72 * @var bool|resource
73 */
74 protected $spawnProc = false;
75
76 /**
77 * @var resource
78 */
79 protected $spawnWrite;
80
81 /**
82 * @var resource
83 */
84 protected $spawnRead;
85
86 /**
87 * @var bool|resource
88 */
89 protected $spawnErr = false;
90
91 /**
92 * @var bool|XmlDumpWriter
93 */
94 protected $xmlwriterobj = false;
95
96 protected $timeExceeded = false;
97 protected $firstPageWritten = false;
98 protected $lastPageWritten = false;
99 protected $checkpointJustWritten = false;
100 protected $checkpointFiles = [];
101
102 /**
103 * @var IMaintainableDatabase
104 */
105 protected $db;
106
107 /**
108 * @param array|null $args For backward compatibility
109 */
110 function __construct( $args = null ) {
111 parent::__construct();
112
113 $this->addDescription( <<<TEXT
114 This script postprocesses XML dumps from dumpBackup.php to add
115 page text which was stubbed out (using --stub).
116
117 XML input is accepted on stdin.
118 XML output is sent to stdout; progress reports are sent to stderr.
119 TEXT
120 );
121 $this->stderr = fopen( "php://stderr", "wt" );
122
123 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
124 'Specify as --stub=<type>:<file>.', false, true );
125 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
126 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
127 false, true );
128 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
129 'out complete page, closing xml file properly, and opening new one' .
130 'with header). This option requires the checkpointfile option.', false, true );
131 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
132 'first pageid written for the first %s (required) and the last pageid written for the ' .
133 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
134 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
135 $this->addOption( 'full', 'Dump all revisions of every page' );
136 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
137 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records, optionally specify ' .
138 'php[,mwscript] paths' );
139 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
140 '(Default: 512KB, Minimum: 4KB)', false, true );
141
142 if ( $args ) {
143 $this->loadWithArgv( $args );
144 $this->processOptions();
145 }
146 }
147
148 /**
149 * @return SqlBlobStore
150 */
151 private function getBlobStore() {
152 return MediaWikiServices::getInstance()->getBlobStore();
153 }
154
155 function execute() {
156 $this->processOptions();
157 $this->dump( true );
158 }
159
160 function processOptions() {
161 parent::processOptions();
162
163 if ( $this->hasOption( 'buffersize' ) ) {
164 $this->bufferSize = max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
165 }
166
167 if ( $this->hasOption( 'prefetch' ) ) {
168 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
169 $this->prefetch = new BaseDump( $url );
170 }
171
172 if ( $this->hasOption( 'stub' ) ) {
173 $this->input = $this->processFileOpt( $this->getOption( 'stub' ) );
174 }
175
176 if ( $this->hasOption( 'maxtime' ) ) {
177 $this->maxTimeAllowed = intval( $this->getOption( 'maxtime' ) ) * 60;
178 }
179
180 if ( $this->hasOption( 'checkpointfile' ) ) {
181 $this->checkpointFiles = $this->getOption( 'checkpointfile' );
182 }
183
184 if ( $this->hasOption( 'current' ) ) {
185 $this->history = WikiExporter::CURRENT;
186 }
187
188 if ( $this->hasOption( 'full' ) ) {
189 $this->history = WikiExporter::FULL;
190 }
191
192 if ( $this->hasOption( 'spawn' ) ) {
193 $this->spawn = true;
194 $val = $this->getOption( 'spawn' );
195 if ( $val !== 1 ) {
196 $this->php = explode( ',', $val, 2 );
197 }
198 }
199 }
200
201 /**
202 * Drop the database connection $this->db and try to get a new one.
203 *
204 * This function tries to get a /different/ connection if this is
205 * possible. Hence, (if this is possible) it switches to a different
206 * failover upon each call.
207 *
208 * This function resets $this->lb and closes all connections on it.
209 *
210 * @throws MWException
211 * @suppress PhanTypeObjectUnsetDeclaredProperty
212 */
213 function rotateDb() {
214 // Cleaning up old connections
215 if ( isset( $this->lb ) ) {
216 $this->lb->closeAll();
217 unset( $this->lb );
218 }
219
220 if ( $this->forcedDb !== null ) {
221 $this->db = $this->forcedDb;
222
223 return;
224 }
225
226 if ( isset( $this->db ) && $this->db->isOpen() ) {
227 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
228 }
229
230 unset( $this->db );
231
232 // Trying to set up new connection.
233 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
234 // individually retrying at different layers of code.
235
236 try {
237 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
238 $this->lb = $lbFactory->newMainLB();
239 } catch ( Exception $e ) {
240 throw new MWException( __METHOD__
241 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
242 }
243
244 try {
245 $this->db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
246 } catch ( Exception $e ) {
247 throw new MWException( __METHOD__
248 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
249 }
250 }
251
252 function initProgress( $history = WikiExporter::FULL ) {
253 parent::initProgress();
254 $this->timeOfCheckpoint = $this->startTime;
255 }
256
257 function dump( $history, $text = WikiExporter::TEXT ) {
258 // Notice messages will foul up your XML output even if they're
259 // relatively harmless.
260 if ( ini_get( 'display_errors' ) ) {
261 ini_set( 'display_errors', 'stderr' );
262 }
263
264 $this->initProgress( $this->history );
265
266 // We are trying to get an initial database connection to avoid that the
267 // first try of this request's first call to getText fails. However, if
268 // obtaining a good DB connection fails it's not a serious issue, as
269 // getText does retry upon failure and can start without having a working
270 // DB connection.
271 try {
272 $this->rotateDb();
273 } catch ( Exception $e ) {
274 // We do not even count this as failure. Just let eventual
275 // watchdogs know.
276 $this->progress( "Getting initial DB connection failed (" .
277 $e->getMessage() . ")" );
278 }
279
280 $this->egress = new ExportProgressFilter( $this->sink, $this );
281
282 // it would be nice to do it in the constructor, oh well. need egress set
283 $this->finalOptionCheck();
284
285 // we only want this so we know how to close a stream :-P
286 $this->xmlwriterobj = new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
287
288 $input = fopen( $this->input, "rt" );
289 $this->readDump( $input );
290
291 if ( $this->spawnProc ) {
292 $this->closeSpawn();
293 }
294
295 $this->report( true );
296 }
297
298 function processFileOpt( $opt ) {
299 $split = explode( ':', $opt, 2 );
300 $val = $split[0];
301 $param = '';
302 if ( count( $split ) === 2 ) {
303 $param = $split[1];
304 }
305 $fileURIs = explode( ';', $param );
306 foreach ( $fileURIs as $URI ) {
307 switch ( $val ) {
308 case "file":
309 $newURI = $URI;
310 break;
311 case "gzip":
312 $newURI = "compress.zlib://$URI";
313 break;
314 case "bzip2":
315 $newURI = "compress.bzip2://$URI";
316 break;
317 case "7zip":
318 $newURI = "mediawiki.compress.7z://$URI";
319 break;
320 default:
321 $newURI = $URI;
322 }
323 $newFileURIs[] = $newURI;
324 }
325 $val = implode( ';', $newFileURIs );
326
327 return $val;
328 }
329
330 /**
331 * Overridden to include prefetch ratio if enabled.
332 */
333 function showReport() {
334 if ( !$this->prefetch ) {
335 parent::showReport();
336
337 return;
338 }
339
340 if ( $this->reporting ) {
341 $now = wfTimestamp( TS_DB );
342 $nowts = microtime( true );
343 $deltaAll = $nowts - $this->startTime;
344 $deltaPart = $nowts - $this->lastTime;
345 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
346 $this->revCountPart = $this->revCount - $this->revCountLast;
347
348 if ( $deltaAll ) {
349 $portion = $this->revCount / $this->maxCount;
350 $eta = $this->startTime + $deltaAll / $portion;
351 $etats = wfTimestamp( TS_DB, intval( $eta ) );
352 if ( $this->fetchCount ) {
353 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
354 } else {
355 $fetchRate = '-';
356 }
357 $pageRate = $this->pageCount / $deltaAll;
358 $revRate = $this->revCount / $deltaAll;
359 } else {
360 $pageRate = '-';
361 $revRate = '-';
362 $etats = '-';
363 $fetchRate = '-';
364 }
365 if ( $deltaPart ) {
366 if ( $this->fetchCountLast ) {
367 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
368 } else {
369 $fetchRatePart = '-';
370 }
371 $pageRatePart = $this->pageCountPart / $deltaPart;
372 $revRatePart = $this->revCountPart / $deltaPart;
373 } else {
374 $fetchRatePart = '-';
375 $pageRatePart = '-';
376 $revRatePart = '-';
377 }
378
379 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
380 $this->progress( sprintf(
381 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
382 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
383 . "prefetched (all|curr), ETA %s [max %d]",
384 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
385 $pageRatePart, $this->revCount, $revRate, $revRatePart,
386 $fetchRate, $fetchRatePart, $etats, $this->maxCount
387 ) );
388 $this->lastTime = $nowts;
389 $this->revCountLast = $this->revCount;
390 $this->prefetchCountLast = $this->prefetchCount;
391 $this->fetchCountLast = $this->fetchCount;
392 }
393 }
394
395 function setTimeExceeded() {
396 $this->timeExceeded = true;
397 }
398
399 function checkIfTimeExceeded() {
400 if ( $this->maxTimeAllowed
401 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
402 ) {
403 return true;
404 }
405
406 return false;
407 }
408
409 function finalOptionCheck() {
410 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
411 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
412 ) {
413 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
414 }
415 foreach ( $this->checkpointFiles as $checkpointFile ) {
416 $count = substr_count( $checkpointFile, "%s" );
417 if ( $count != 2 ) {
418 throw new MWException( "Option checkpointfile must contain two '%s' "
419 . "for substitution of first and last pageids, count is $count instead, "
420 . "file is $checkpointFile.\n" );
421 }
422 }
423
424 if ( $this->checkpointFiles ) {
425 $filenameList = (array)$this->egress->getFilenames();
426 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
427 throw new MWException( "One checkpointfile must be specified "
428 . "for each output option, if maxtime is used.\n" );
429 }
430 }
431 }
432
433 /**
434 * @throws MWException Failure to parse XML input
435 * @param resource $input
436 * @return bool
437 */
438 function readDump( $input ) {
439 $this->buffer = "";
440 $this->openElement = false;
441 $this->atStart = true;
442 $this->state = "";
443 $this->lastName = "";
444 $this->thisPage = 0;
445 $this->thisRev = 0;
446 $this->thisRevModel = null;
447 $this->thisRevFormat = null;
448
449 $parser = xml_parser_create( "UTF-8" );
450 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
451
452 xml_set_element_handler(
453 $parser,
454 [ $this, 'startElement' ],
455 [ $this, 'endElement' ]
456 );
457 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
458
459 $offset = 0; // for context extraction on error reporting
460 do {
461 if ( $this->checkIfTimeExceeded() ) {
462 $this->setTimeExceeded();
463 }
464 $chunk = fread( $input, $this->bufferSize );
465 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
466 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
467
468 $byte = xml_get_current_byte_index( $parser );
469 $msg = wfMessage( 'xml-error-string',
470 'XML import parse failure',
471 xml_get_current_line_number( $parser ),
472 xml_get_current_column_number( $parser ),
473 $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
474 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
475
476 xml_parser_free( $parser );
477
478 throw new MWException( $msg );
479 }
480 $offset += strlen( $chunk );
481 } while ( $chunk !== false && !feof( $input ) );
482 if ( $this->maxTimeAllowed ) {
483 $filenameList = (array)$this->egress->getFilenames();
484 // we wrote some stuff after last checkpoint that needs renamed
485 if ( file_exists( $filenameList[0] ) ) {
486 $newFilenames = [];
487 # we might have just written the header and footer and had no
488 # pages or revisions written... perhaps they were all deleted
489 # there's no pageID 0 so we use that. the caller is responsible
490 # for deciding what to do with a file containing only the
491 # siteinfo information and the mw tags.
492 if ( !$this->firstPageWritten ) {
493 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
494 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
495 } else {
496 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
497 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
498 }
499
500 $filenameCount = count( $filenameList );
501 for ( $i = 0; $i < $filenameCount; $i++ ) {
502 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
503 $fileinfo = pathinfo( $filenameList[$i] );
504 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
505 }
506 $this->egress->closeAndRename( $newFilenames );
507 }
508 }
509 xml_parser_free( $parser );
510
511 return true;
512 }
513
514 /**
515 * Applies applicable export transformations to $text.
516 *
517 * @param string $text
518 * @param string $model
519 * @param string|null $format
520 *
521 * @return string
522 */
523 private function exportTransform( $text, $model, $format = null ) {
524 try {
525 $handler = ContentHandler::getForModelID( $model );
526 $text = $handler->exportTransform( $text, $format );
527 }
528 catch ( MWException $ex ) {
529 $this->progress(
530 "Unable to apply export transformation for content model '$model': " .
531 $ex->getMessage()
532 );
533 }
534
535 return $text;
536 }
537
538 /**
539 * Tries to load revision text.
540 * Export transformations are applied if the content model is given or can be
541 * determined from the database.
542 *
543 * Upon errors, retries (Up to $this->maxFailures tries each call).
544 * If still no good revision could be found even after this retrying, "" is returned.
545 * If no good revision text could be returned for
546 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
547 * is thrown.
548 *
549 * @param int|string $id Content address, or text row ID.
550 * @param string|bool|null $model The content model used to determine
551 * applicable export transformations.
552 * If $model is null, it will be determined from the database.
553 * @param string|null $format The content format used when applying export transformations.
554 *
555 * @throws MWException
556 * @return string The revision text for $id, or ""
557 */
558 function getText( $id, $model = null, $format = null ) {
559 global $wgContentHandlerUseDB;
560
561 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
562 $text = false; // The candidate for a good text. false if no proper value.
563 $failures = 0; // The number of times, this invocation of getText already failed.
564
565 // The number of times getText failed without yielding a good text in between.
566 static $consecutiveFailedTextRetrievals = 0;
567
568 $this->fetchCount++;
569
570 // To allow to simply return on success and do not have to worry about book keeping,
571 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
572 // the old value, so we can restore it, if problems occur (See after the while loop).
573 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
574 $consecutiveFailedTextRetrievals = 0;
575
576 if ( $model === null && $wgContentHandlerUseDB ) {
577 // TODO: MCR: use content table
578 $row = $this->db->selectRow(
579 'revision',
580 [ 'rev_content_model', 'rev_content_format' ],
581 [ 'rev_id' => $this->thisRev ],
582 __METHOD__
583 );
584
585 if ( $row ) {
586 $model = $row->rev_content_model;
587 $format = $row->rev_content_format;
588 }
589 }
590
591 if ( $model === null || $model === '' ) {
592 $model = false;
593 }
594
595 while ( $failures < $this->maxFailures ) {
596 // As soon as we found a good text for the $id, we will return immediately.
597 // Hence, if we make it past the try catch block, we know that we did not
598 // find a good text.
599
600 try {
601 // Step 1: Get some text (or reuse from previous iteratuon if checking
602 // for plausibility failed)
603
604 // Trying to get prefetch, if it has not been tried before
605 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
606 $prefetchNotTried = false;
607 $tryIsPrefetch = true;
608 $text = $this->prefetch->prefetch( (int)$this->thisPage, (int)$this->thisRev );
609
610 if ( $text === null ) {
611 $text = false;
612 }
613
614 if ( is_string( $text ) && $model !== false ) {
615 // Apply export transformation to text coming from an old dump.
616 // The purpose of this transformation is to convert up from legacy
617 // formats, which may still be used in the older dump that is used
618 // for pre-fetching. Applying the transformation again should not
619 // interfere with content that is already in the correct form.
620 $text = $this->exportTransform( $text, $model, $format );
621 }
622 }
623
624 if ( $text === false ) {
625 // Fallback to asking the database
626 $tryIsPrefetch = false;
627 if ( $this->spawn ) {
628 $text = $this->getTextSpawned( $id );
629 } else {
630 $text = $this->getTextDb( $id );
631 }
632
633 if ( $text !== false && $model !== false ) {
634 // Apply export transformation to text coming from the database.
635 // Prefetched text should already have transformations applied.
636 $text = $this->exportTransform( $text, $model, $format );
637 }
638
639 // No more checks for texts from DB for now.
640 // If we received something that is not false,
641 // We treat it as good text, regardless of whether it actually is or is not
642 if ( $text !== false ) {
643 return $text;
644 }
645 }
646
647 if ( $text === false ) {
648 throw new MWException( "Generic error while obtaining text for id " . $id );
649 }
650
651 // We received a good candidate for the text of $id via some method
652
653 // Step 2: Checking for plausibility and return the text if it is
654 // plausible
655 $revID = intval( $this->thisRev );
656 if ( !isset( $this->db ) ) {
657 throw new MWException( "No database available" );
658 }
659
660 if ( $model !== CONTENT_MODEL_WIKITEXT ) {
661 $revLength = strlen( $text );
662 } else {
663 $revLength = $this->db->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
664 }
665
666 if ( strlen( $text ) == $revLength ) {
667 if ( $tryIsPrefetch ) {
668 $this->prefetchCount++;
669 }
670
671 return $text;
672 }
673
674 $text = false;
675 throw new MWException( "Received text is unplausible for id " . $id );
676 } catch ( Exception $e ) {
677 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
678 if ( $failures + 1 < $this->maxFailures ) {
679 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
680 }
681 $this->progress( $msg );
682 }
683
684 // Something went wrong; we did not a text that was plausible :(
685 $failures++;
686
687 // A failure in a prefetch hit does not warrant resetting db connection etc.
688 if ( !$tryIsPrefetch ) {
689 // After backing off for some time, we try to reboot the whole process as
690 // much as possible to not carry over failures from one part to the other
691 // parts
692 sleep( $this->failureTimeout );
693 try {
694 $this->rotateDb();
695 if ( $this->spawn ) {
696 $this->closeSpawn();
697 $this->openSpawn();
698 }
699 } catch ( Exception $e ) {
700 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
701 " Trying to continue anyways" );
702 }
703 }
704 }
705
706 // Retirieving a good text for $id failed (at least) maxFailures times.
707 // We abort for this $id.
708
709 // Restoring the consecutive failures, and maybe aborting, if the dump
710 // is too broken.
711 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
712 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
713 throw new MWException( "Graceful storage failure" );
714 }
715
716 return "";
717 }
718
719 /**
720 * Loads the serialized content from storage.
721 *
722 * @param int|string $id Content address, or text row ID.
723 * @return bool|string
724 */
725 private function getTextDb( $id ) {
726 $store = $this->getBlobStore();
727 $address = ( is_int( $id ) || strpos( $id, ':' ) === false )
728 ? SqlBlobStore::makeAddressFromTextId( (int)$id )
729 : $id;
730
731 try {
732 $text = $store->getBlob( $address );
733
734 $stripped = str_replace( "\r", "", $text );
735 $normalized = MediaWikiServices::getInstance()->getContentLanguage()
736 ->normalize( $stripped );
737
738 return $normalized;
739 } catch ( BlobAccessException $ex ) {
740 // XXX: log a warning?
741 return false;
742 }
743 }
744
745 /**
746 * @param int|string $address Content address, or text row ID.
747 * @return bool|string
748 */
749 private function getTextSpawned( $address ) {
750 Wikimedia\suppressWarnings();
751 if ( !$this->spawnProc ) {
752 // First time?
753 $this->openSpawn();
754 }
755 $text = $this->getTextSpawnedOnce( $address );
756 Wikimedia\restoreWarnings();
757
758 return $text;
759 }
760
761 function openSpawn() {
762 global $IP;
763
764 $wiki = WikiMap::getWikiIdFromDbDomain( WikiMap::getCurrentWikiDbDomain() );
765 if ( count( $this->php ) == 2 ) {
766 $mwscriptpath = $this->php[1];
767 } else {
768 $mwscriptpath = "$IP/../multiversion/MWScript.php";
769 }
770 if ( file_exists( $mwscriptpath ) ) {
771 $cmd = implode( " ",
772 array_map( [ Shell::class, 'escape' ],
773 [
774 $this->php[0],
775 $mwscriptpath,
776 "fetchText.php",
777 '--wiki', $wiki ] ) );
778 } else {
779 $cmd = implode( " ",
780 array_map( [ Shell::class, 'escape' ],
781 [
782 $this->php[0],
783 "$IP/maintenance/fetchText.php",
784 '--wiki', $wiki ] ) );
785 }
786 $spec = [
787 0 => [ "pipe", "r" ],
788 1 => [ "pipe", "w" ],
789 2 => [ "file", "/dev/null", "a" ] ];
790 $pipes = [];
791
792 $this->progress( "Spawning database subprocess: $cmd" );
793 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
794 if ( !$this->spawnProc ) {
795 $this->progress( "Subprocess spawn failed." );
796
797 return false;
798 }
799 list(
800 $this->spawnWrite, // -> stdin
801 $this->spawnRead, // <- stdout
802 ) = $pipes;
803
804 return true;
805 }
806
807 private function closeSpawn() {
808 Wikimedia\suppressWarnings();
809 if ( $this->spawnRead ) {
810 fclose( $this->spawnRead );
811 }
812 $this->spawnRead = null;
813 if ( $this->spawnWrite ) {
814 fclose( $this->spawnWrite );
815 }
816 $this->spawnWrite = null;
817 if ( $this->spawnErr ) {
818 fclose( $this->spawnErr );
819 }
820 $this->spawnErr = false;
821 if ( $this->spawnProc ) {
822 pclose( $this->spawnProc );
823 }
824 $this->spawnProc = false;
825 Wikimedia\restoreWarnings();
826 }
827
828 /**
829 * @param int|string $address Content address, or text row ID.
830 * @return bool|string
831 */
832 private function getTextSpawnedOnce( $address ) {
833 if ( is_int( $address ) || intval( $address ) ) {
834 $address = SqlBlobStore::makeAddressFromTextId( (int)$address );
835 }
836
837 $ok = fwrite( $this->spawnWrite, "$address\n" );
838 // $this->progress( ">> $id" );
839 if ( !$ok ) {
840 return false;
841 }
842
843 $ok = fflush( $this->spawnWrite );
844 // $this->progress( ">> [flush]" );
845 if ( !$ok ) {
846 return false;
847 }
848
849 // check that the text address they are sending is the one we asked for
850 // this avoids out of sync revision text errors we have encountered in the past
851 $newAddress = fgets( $this->spawnRead );
852 if ( $newAddress === false ) {
853 return false;
854 }
855 $newAddress = trim( $newAddress );
856 if ( strpos( $newAddress, ':' ) === false ) {
857 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
858 }
859
860 if ( $newAddress !== $address ) {
861 return false;
862 }
863
864 $len = fgets( $this->spawnRead );
865 // $this->progress( "<< " . trim( $len ) );
866 if ( $len === false ) {
867 return false;
868 }
869
870 $nbytes = intval( $len );
871 // actual error, not zero-length text
872 if ( $nbytes < 0 ) {
873 return false;
874 }
875
876 $text = "";
877
878 // Subprocess may not send everything at once, we have to loop.
879 while ( $nbytes > strlen( $text ) ) {
880 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
881 if ( $buffer === false ) {
882 break;
883 }
884 $text .= $buffer;
885 }
886
887 $gotbytes = strlen( $text );
888 if ( $gotbytes != $nbytes ) {
889 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
890
891 return false;
892 }
893
894 // Do normalization in the dump thread...
895 $stripped = str_replace( "\r", "", $text );
896 $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
897 normalize( $stripped );
898
899 return $normalized;
900 }
901
902 function startElement( $parser, $name, $attribs ) {
903 $this->checkpointJustWritten = false;
904
905 $this->clearOpenElement( null );
906 $this->lastName = $name;
907
908 if ( $name == 'revision' ) {
909 $this->state = $name;
910 $this->egress->writeOpenPage( null, $this->buffer );
911 $this->buffer = "";
912 } elseif ( $name == 'page' ) {
913 $this->state = $name;
914 if ( $this->atStart ) {
915 $this->egress->writeOpenStream( $this->buffer );
916 $this->buffer = "";
917 $this->atStart = false;
918 }
919 }
920
921 if ( $name == "text" && isset( $attribs['id'] ) ) {
922 $id = $attribs['id'];
923 $model = trim( $this->thisRevModel );
924 $format = trim( $this->thisRevFormat );
925
926 $model = $model === '' ? null : $model;
927 $format = $format === '' ? null : $format;
928
929 $text = $this->getText( $id, $model, $format );
930 $this->openElement = [ $name, [ 'xml:space' => 'preserve' ] ];
931 if ( strlen( $text ) > 0 ) {
932 $this->characterData( $parser, $text );
933 }
934 } else {
935 $this->openElement = [ $name, $attribs ];
936 }
937 }
938
939 function endElement( $parser, $name ) {
940 $this->checkpointJustWritten = false;
941
942 if ( $this->openElement ) {
943 $this->clearOpenElement( "" );
944 } else {
945 $this->buffer .= "</$name>";
946 }
947
948 if ( $name == 'revision' ) {
949 $this->egress->writeRevision( null, $this->buffer );
950 $this->buffer = "";
951 $this->thisRev = "";
952 $this->thisRevModel = null;
953 $this->thisRevFormat = null;
954 } elseif ( $name == 'page' ) {
955 if ( !$this->firstPageWritten ) {
956 $this->firstPageWritten = trim( $this->thisPage );
957 }
958 $this->lastPageWritten = trim( $this->thisPage );
959 if ( $this->timeExceeded ) {
960 $this->egress->writeClosePage( $this->buffer );
961 // nasty hack, we can't just write the chardata after the
962 // page tag, it will include leading blanks from the next line
963 $this->egress->sink->write( "\n" );
964
965 $this->buffer = $this->xmlwriterobj->closeStream();
966 $this->egress->writeCloseStream( $this->buffer );
967
968 $this->buffer = "";
969 $this->thisPage = "";
970 // this could be more than one file if we had more than one output arg
971
972 $filenameList = (array)$this->egress->getFilenames();
973 $newFilenames = [];
974 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
975 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
976 $filenamesCount = count( $filenameList );
977 for ( $i = 0; $i < $filenamesCount; $i++ ) {
978 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
979 $fileinfo = pathinfo( $filenameList[$i] );
980 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
981 }
982 $this->egress->closeRenameAndReopen( $newFilenames );
983 $this->buffer = $this->xmlwriterobj->openStream();
984 $this->timeExceeded = false;
985 $this->timeOfCheckpoint = $this->lastTime;
986 $this->firstPageWritten = false;
987 $this->checkpointJustWritten = true;
988 } else {
989 $this->egress->writeClosePage( $this->buffer );
990 $this->buffer = "";
991 $this->thisPage = "";
992 }
993 } elseif ( $name == 'mediawiki' ) {
994 $this->egress->writeCloseStream( $this->buffer );
995 $this->buffer = "";
996 }
997 }
998
999 function characterData( $parser, $data ) {
1000 $this->clearOpenElement( null );
1001 if ( $this->lastName == "id" ) {
1002 if ( $this->state == "revision" ) {
1003 $this->thisRev .= $data;
1004 } elseif ( $this->state == "page" ) {
1005 $this->thisPage .= $data;
1006 }
1007 } elseif ( $this->lastName == "model" ) {
1008 $this->thisRevModel .= $data;
1009 } elseif ( $this->lastName == "format" ) {
1010 $this->thisRevFormat .= $data;
1011 }
1012
1013 // have to skip the newline left over from closepagetag line of
1014 // end of checkpoint files. nasty hack!!
1015 if ( $this->checkpointJustWritten ) {
1016 if ( $data[0] == "\n" ) {
1017 $data = substr( $data, 1 );
1018 }
1019 $this->checkpointJustWritten = false;
1020 }
1021 $this->buffer .= htmlspecialchars( $data );
1022 }
1023
1024 function clearOpenElement( $style ) {
1025 if ( $this->openElement ) {
1026 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
1027 $this->openElement = false;
1028 }
1029 }
1030 }