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