dumpTextPass.php 29 KB

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