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