Debian Codegraph @

maintenance/includes/TextPassDumper.php

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