dumpTextPass.php 29 KB

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