backup.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. /**
  3. * Base classes for database dumpers
  4. *
  5. * Copyright © 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 Dump Maintenance
  25. */
  26. require_once __DIR__ . '/Maintenance.php';
  27. require_once __DIR__ . '/../includes/export/DumpFilter.php';
  28. /**
  29. * @ingroup Dump Maintenance
  30. */
  31. class BackupDumper extends Maintenance {
  32. public $reporting = true;
  33. public $pages = null; // all pages
  34. public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
  35. public $skipFooter = false; // don't output </mediawiki>
  36. public $startId = 0;
  37. public $endId = 0;
  38. public $revStartId = 0;
  39. public $revEndId = 0;
  40. public $dumpUploads = false;
  41. public $dumpUploadFileContents = false;
  42. protected $reportingInterval = 100;
  43. protected $pageCount = 0;
  44. protected $revCount = 0;
  45. protected $server = null; // use default
  46. protected $sink = null; // Output filters
  47. protected $lastTime = 0;
  48. protected $pageCountLast = 0;
  49. protected $revCountLast = 0;
  50. protected $outputTypes = [];
  51. protected $filterTypes = [];
  52. protected $ID = 0;
  53. /**
  54. * The dependency-injected database to use.
  55. *
  56. * @var DatabaseBase|null
  57. *
  58. * @see self::setDB
  59. */
  60. protected $forcedDb = null;
  61. /** @var LoadBalancer */
  62. protected $lb;
  63. // @todo Unused?
  64. private $stubText = false; // include rev_text_id instead of text; for 2-pass dump
  65. /**
  66. * @param array $args For backward compatibility
  67. */
  68. function __construct( $args = null ) {
  69. parent::__construct();
  70. $this->stderr = fopen( "php://stderr", "wt" );
  71. // Built-in output and filter plugins
  72. $this->registerOutput( 'file', 'DumpFileOutput' );
  73. $this->registerOutput( 'gzip', 'DumpGZipOutput' );
  74. $this->registerOutput( 'bzip2', 'DumpBZip2Output' );
  75. $this->registerOutput( 'dbzip2', 'DumpDBZip2Output' );
  76. $this->registerOutput( '7zip', 'Dump7ZipOutput' );
  77. $this->registerFilter( 'latest', 'DumpLatestFilter' );
  78. $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
  79. $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
  80. // These three can be specified multiple times
  81. $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
  82. false, true, false, true );
  83. $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
  84. '<type>s: file, gzip, bzip2, 7zip, dbzip2', false, true, false, true );
  85. $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
  86. '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
  87. $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
  88. 'Default: 100.', false, true );
  89. $this->addOption( 'server', 'Force reading from MySQL server', false, true );
  90. $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
  91. '-mx option to 7za command.', false, true );
  92. if ( $args ) {
  93. // Args should be loaded and processed so that dump() can be called directly
  94. // instead of execute()
  95. $this->loadWithArgv( $args );
  96. $this->processOptions();
  97. }
  98. }
  99. /**
  100. * @param string $name
  101. * @param string $class Name of output filter plugin class
  102. */
  103. function registerOutput( $name, $class ) {
  104. $this->outputTypes[$name] = $class;
  105. }
  106. /**
  107. * @param string $name
  108. * @param string $class Name of filter plugin class
  109. */
  110. function registerFilter( $name, $class ) {
  111. $this->filterTypes[$name] = $class;
  112. }
  113. /**
  114. * Load a plugin and register it
  115. *
  116. * @param string $class Name of plugin class; must have a static 'register'
  117. * method that takes a BackupDumper as a parameter.
  118. * @param string $file Full or relative path to the PHP file to load, or empty
  119. */
  120. function loadPlugin( $class, $file ) {
  121. if ( $file != '' ) {
  122. require_once $file;
  123. }
  124. $register = [ $class, 'register' ];
  125. call_user_func_array( $register, [ $this ] );
  126. }
  127. function execute() {
  128. throw new MWException( 'execute() must be overridden in subclasses' );
  129. }
  130. /**
  131. * Processes arguments and sets $this->$sink accordingly
  132. */
  133. function processOptions() {
  134. $sink = null;
  135. $sinks = [];
  136. $options = $this->orderedOptions;
  137. foreach ( $options as $arg ) {
  138. $opt = $arg[0];
  139. $param = $arg[1];
  140. switch ( $opt ) {
  141. case 'plugin':
  142. $val = explode( ':', $param );
  143. if ( count( $val ) === 1 ) {
  144. $this->loadPlugin( $val[0] );
  145. } elseif ( count( $val ) === 2 ) {
  146. $this->loadPlugin( $val[0], $val[1] );
  147. } else {
  148. $this->fatalError( 'Invalid plugin parameter' );
  149. return;
  150. }
  151. break;
  152. case 'output':
  153. $split = explode( ':', $param, 2 );
  154. if ( count( $split ) !== 2 ) {
  155. $this->fatalError( 'Invalid output parameter' );
  156. }
  157. list( $type, $file ) = $split;
  158. if ( !is_null( $sink ) ) {
  159. $sinks[] = $sink;
  160. }
  161. if ( !isset( $this->outputTypes[$type] ) ) {
  162. $this->fatalError( "Unrecognized output sink type '$type'" );
  163. }
  164. $class = $this->outputTypes[$type];
  165. if ( $type === "7zip" ) {
  166. $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
  167. } else {
  168. $sink = new $class( $file );
  169. }
  170. break;
  171. case 'filter':
  172. if ( is_null( $sink ) ) {
  173. $sink = new DumpOutput();
  174. }
  175. $split = explode( ':', $param );
  176. $key = $split[0];
  177. if ( !isset( $this->filterTypes[$key] ) ) {
  178. $this->fatalError( "Unrecognized filter type '$key'" );
  179. }
  180. $type = $this->filterTypes[$key];
  181. if ( count( $split ) === 1 ) {
  182. $filter = new $type( $sink );
  183. } elseif ( count( $split ) === 2 ) {
  184. $filter = new $type( $sink, $split[1] );
  185. } else {
  186. $this->fatalError( 'Invalid filter parameter' );
  187. }
  188. // references are lame in php...
  189. unset( $sink );
  190. $sink = $filter;
  191. break;
  192. }
  193. }
  194. if ( $this->hasOption( 'report' ) ) {
  195. $this->reportingInterval = intval( $this->getOption( 'report' ) );
  196. }
  197. if ( $this->hasOption( 'server' ) ) {
  198. $this->server = $this->getOption( 'server' );
  199. }
  200. if ( is_null( $sink ) ) {
  201. $sink = new DumpOutput();
  202. }
  203. $sinks[] = $sink;
  204. if ( count( $sinks ) > 1 ) {
  205. $this->sink = new DumpMultiWriter( $sinks );
  206. } else {
  207. $this->sink = $sink;
  208. }
  209. }
  210. function dump( $history, $text = WikiExporter::TEXT ) {
  211. # Notice messages will foul up your XML output even if they're
  212. # relatively harmless.
  213. if ( ini_get( 'display_errors' ) ) {
  214. ini_set( 'display_errors', 'stderr' );
  215. }
  216. $this->initProgress( $history );
  217. $db = $this->backupDb();
  218. $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
  219. $exporter->dumpUploads = $this->dumpUploads;
  220. $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
  221. $wrapper = new ExportProgressFilter( $this->sink, $this );
  222. $exporter->setOutputSink( $wrapper );
  223. if ( !$this->skipHeader ) {
  224. $exporter->openStream();
  225. }
  226. # Log item dumps: all or by range
  227. if ( $history & WikiExporter::LOGS ) {
  228. if ( $this->startId || $this->endId ) {
  229. $exporter->logsByRange( $this->startId, $this->endId );
  230. } else {
  231. $exporter->allLogs();
  232. }
  233. } elseif ( is_null( $this->pages ) ) {
  234. # Page dumps: all or by page ID range
  235. if ( $this->startId || $this->endId ) {
  236. $exporter->pagesByRange( $this->startId, $this->endId );
  237. } elseif ( $this->revStartId || $this->revEndId ) {
  238. $exporter->revsByRange( $this->revStartId, $this->revEndId );
  239. } else {
  240. $exporter->allPages();
  241. }
  242. } else {
  243. # Dump of specific pages
  244. $exporter->pagesByName( $this->pages );
  245. }
  246. if ( !$this->skipFooter ) {
  247. $exporter->closeStream();
  248. }
  249. $this->report( true );
  250. }
  251. /**
  252. * Initialise starting time and maximum revision count.
  253. * We'll make ETA calculations based an progress, assuming relatively
  254. * constant per-revision rate.
  255. * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
  256. */
  257. function initProgress( $history = WikiExporter::FULL ) {
  258. $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
  259. $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
  260. $dbr = $this->forcedDb;
  261. if ( $this->forcedDb === null ) {
  262. $dbr = wfGetDB( DB_SLAVE );
  263. }
  264. $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
  265. $this->startTime = microtime( true );
  266. $this->lastTime = $this->startTime;
  267. $this->ID = getmypid();
  268. }
  269. /**
  270. * @todo Fixme: the --server parameter is currently not respected, as it
  271. * doesn't seem terribly easy to ask the load balancer for a particular
  272. * connection by name.
  273. * @return DatabaseBase
  274. */
  275. function backupDb() {
  276. if ( $this->forcedDb !== null ) {
  277. return $this->forcedDb;
  278. }
  279. $this->lb = wfGetLBFactory()->newMainLB();
  280. $db = $this->lb->getConnection( DB_SLAVE, 'dump' );
  281. // Discourage the server from disconnecting us if it takes a long time
  282. // to read out the big ol' batch query.
  283. $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
  284. return $db;
  285. }
  286. /**
  287. * Force the dump to use the provided database connection for database
  288. * operations, wherever possible.
  289. *
  290. * @param DatabaseBase|null $db (Optional) the database connection to use. If null, resort to
  291. * use the globally provided ways to get database connections.
  292. */
  293. function setDB( IDatabase $db = null ) {
  294. parent::setDB( $db );
  295. $this->forcedDb = $db;
  296. }
  297. function __destruct() {
  298. if ( isset( $this->lb ) ) {
  299. $this->lb->closeAll();
  300. }
  301. }
  302. function backupServer() {
  303. global $wgDBserver;
  304. return $this->server
  305. ? $this->server
  306. : $wgDBserver;
  307. }
  308. function reportPage() {
  309. $this->pageCount++;
  310. }
  311. function revCount() {
  312. $this->revCount++;
  313. $this->report();
  314. }
  315. function report( $final = false ) {
  316. if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
  317. $this->showReport();
  318. }
  319. }
  320. function showReport() {
  321. if ( $this->reporting ) {
  322. $now = wfTimestamp( TS_DB );
  323. $nowts = microtime( true );
  324. $deltaAll = $nowts - $this->startTime;
  325. $deltaPart = $nowts - $this->lastTime;
  326. $this->pageCountPart = $this->pageCount - $this->pageCountLast;
  327. $this->revCountPart = $this->revCount - $this->revCountLast;
  328. if ( $deltaAll ) {
  329. $portion = $this->revCount / $this->maxCount;
  330. $eta = $this->startTime + $deltaAll / $portion;
  331. $etats = wfTimestamp( TS_DB, intval( $eta ) );
  332. $pageRate = $this->pageCount / $deltaAll;
  333. $revRate = $this->revCount / $deltaAll;
  334. } else {
  335. $pageRate = '-';
  336. $revRate = '-';
  337. $etats = '-';
  338. }
  339. if ( $deltaPart ) {
  340. $pageRatePart = $this->pageCountPart / $deltaPart;
  341. $revRatePart = $this->revCountPart / $deltaPart;
  342. } else {
  343. $pageRatePart = '-';
  344. $revRatePart = '-';
  345. }
  346. $this->progress( sprintf(
  347. "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
  348. . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
  349. $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
  350. $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
  351. $this->maxCount
  352. ) );
  353. $this->lastTime = $nowts;
  354. $this->revCountLast = $this->revCount;
  355. }
  356. }
  357. function progress( $string ) {
  358. if ( $this->reporting ) {
  359. fwrite( $this->stderr, $string . "\n" );
  360. }
  361. }
  362. function fatalError( $msg ) {
  363. $this->error( "$msg\n", 1 );
  364. }
  365. }
  366. class ExportProgressFilter extends DumpFilter {
  367. function __construct( &$sink, &$progress ) {
  368. parent::__construct( $sink );
  369. $this->progress = $progress;
  370. }
  371. function writeClosePage( $string ) {
  372. parent::writeClosePage( $string );
  373. $this->progress->reportPage();
  374. }
  375. function writeRevision( $rev, $string ) {
  376. parent::writeRevision( $rev, $string );
  377. $this->progress->revCount();
  378. }
  379. }