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