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