3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Bail on old versions of PHP, or if composer has not been run yet to install
25 require_once __DIR__
. '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'cli' );
28 use MediaWiki\Shell\Shell
;
29 use Wikimedia\Rdbms\DBReplicationWaitError
;
32 * @defgroup MaintenanceArchive Maintenance archives
33 * @ingroup Maintenance
36 // Define this so scripts can easily find doMaintenance.php
37 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
38 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
42 use Wikimedia\Rdbms\IDatabase
;
43 use MediaWiki\Logger\LoggerFactory
;
44 use MediaWiki\MediaWikiServices
;
45 use Wikimedia\Rdbms\LBFactory
;
46 use Wikimedia\Rdbms\IMaintainableDatabase
;
49 * Abstract maintenance class for quickly writing and churning out
50 * maintenance scripts with minimal effort. All that _must_ be defined
51 * is the execute() method. See docs/maintenance.txt for more info
52 * and a quick demo of how to use it.
55 * @ingroup Maintenance
57 abstract class Maintenance
{
59 * Constants for DB access type
60 * @see Maintenance::getDbType()
66 // Const for getStdin()
67 const STDIN_ALL
= 'all';
69 // This is the desired params
70 protected $mParams = [];
72 // Array of mapping short parameters to long ones
73 protected $mShortParamsMap = [];
75 // Array of desired args
76 protected $mArgList = [];
78 // This is the list of options that were actually passed
79 protected $mOptions = [];
81 // This is the list of arguments that were actually passed
82 protected $mArgs = [];
84 // Name of the script currently running
87 // Special vars for params that are always used
88 protected $mQuiet = false;
89 protected $mDbUser, $mDbPass;
91 // A description of the script, children should change this via addDescription()
92 protected $mDescription = '';
94 // Have we already loaded our user input?
95 protected $mInputLoaded = false;
98 * Batch size. If a script supports this, they should set
99 * a default with setBatchSize()
103 protected $mBatchSize = null;
105 // Generic options added by addDefaultParams()
106 private $mGenericParameters = [];
107 // Generic options which might or not be supported by the script
108 private $mDependantParameters = [];
111 * Used by getDB() / setDB()
112 * @var IMaintainableDatabase
116 /** @var float UNIX timestamp */
117 private $lastReplicationWait = 0.0;
120 * Used when creating separate schema files.
126 * Accessible via getConfig()
133 * @see Maintenance::requireExtension
136 private $requiredExtensions = [];
139 * Used to read the options in the order they were passed.
140 * Useful for option chaining (Ex. dumpBackup.php). It will
141 * be an empty array if the options are passed in through
142 * loadParamsAndArgs( $self, $opts, $args ).
144 * This is an array of arrays where
145 * 0 => the option and 1 => parameter value.
149 public $orderedOptions = [];
152 * Default constructor. Children should call this *first* if implementing
153 * their own constructors
155 public function __construct() {
156 // Setup $IP, using MW_INSTALL_PATH if it exists
158 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
159 ?
getenv( 'MW_INSTALL_PATH' )
160 : realpath( __DIR__
. '/..' );
162 $this->addDefaultParams();
163 register_shutdown_function( [ $this, 'outputChanneled' ], false );
167 * Should we execute the maintenance script, or just allow it to be included
168 * as a standalone class? It checks that the call stack only includes this
169 * function and "requires" (meaning was called from the file scope)
173 public static function shouldExecute() {
174 global $wgCommandLineMode;
176 if ( !function_exists( 'debug_backtrace' ) ) {
177 // If someone has a better idea...
178 return $wgCommandLineMode;
181 $bt = debug_backtrace();
182 $count = count( $bt );
184 return false; // sanity
186 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
187 return false; // last call should be to this function
189 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
190 for ( $i = 1; $i < $count; $i++
) {
191 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
192 return false; // previous calls should all be "requires"
200 * Do the actual work. All child classes will need to implement this
202 abstract public function execute();
205 * Add a parameter to the script. Will be displayed on --help
206 * with the associated description
208 * @param string $name The name of the param (help, version, etc)
209 * @param string $description The description of the param to show on --help
210 * @param bool $required Is the param required?
211 * @param bool $withArg Is an argument required with this option?
212 * @param string|bool $shortName Character to use as short name
213 * @param bool $multiOccurrence Can this option be passed multiple times?
215 protected function addOption( $name, $description, $required = false,
216 $withArg = false, $shortName = false, $multiOccurrence = false
218 $this->mParams
[$name] = [
219 'desc' => $description,
220 'require' => $required,
221 'withArg' => $withArg,
222 'shortName' => $shortName,
223 'multiOccurrence' => $multiOccurrence
226 if ( $shortName !== false ) {
227 $this->mShortParamsMap
[$shortName] = $name;
232 * Checks to see if a particular param exists.
233 * @param string $name The name of the param
236 protected function hasOption( $name ) {
237 return isset( $this->mOptions
[$name] );
241 * Get an option, or return the default.
243 * If the option was added to support multiple occurrences,
244 * this will return an array.
246 * @param string $name The name of the param
247 * @param mixed $default Anything you want, default null
250 protected function getOption( $name, $default = null ) {
251 if ( $this->hasOption( $name ) ) {
252 return $this->mOptions
[$name];
254 // Set it so we don't have to provide the default again
255 $this->mOptions
[$name] = $default;
257 return $this->mOptions
[$name];
262 * Add some args that are needed
263 * @param string $arg Name of the arg, like 'start'
264 * @param string $description Short description of the arg
265 * @param bool $required Is this required?
267 protected function addArg( $arg, $description, $required = true ) {
268 $this->mArgList
[] = [
270 'desc' => $description,
271 'require' => $required
276 * Remove an option. Useful for removing options that won't be used in your script.
277 * @param string $name The option to remove.
279 protected function deleteOption( $name ) {
280 unset( $this->mParams
[$name] );
284 * Set the description text.
285 * @param string $text The text of the description
287 protected function addDescription( $text ) {
288 $this->mDescription
= $text;
292 * Does a given argument exist?
293 * @param int $argId The integer value (from zero) for the arg
296 protected function hasArg( $argId = 0 ) {
297 return isset( $this->mArgs
[$argId] );
302 * @param int $argId The integer value (from zero) for the arg
303 * @param mixed $default The default if it doesn't exist
306 protected function getArg( $argId = 0, $default = null ) {
307 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
317 protected function getBatchSize() {
318 return $this->mBatchSize
;
322 * Set the batch size.
323 * @param int $s The number of operations to do in a batch
325 protected function setBatchSize( $s = 0 ) {
326 $this->mBatchSize
= $s;
328 // If we support $mBatchSize, show the option.
329 // Used to be in addDefaultParams, but in order for that to
330 // work, subclasses would have to call this function in the constructor
331 // before they called parent::__construct which is just weird
332 // (and really wasn't done).
333 if ( $this->mBatchSize
) {
334 $this->addOption( 'batch-size', 'Run this many operations ' .
335 'per batch, default: ' . $this->mBatchSize
, false, true );
336 if ( isset( $this->mParams
['batch-size'] ) ) {
337 // This seems a little ugly...
338 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
344 * Get the script's name
347 public function getName() {
352 * Return input from stdin.
353 * @param int $len The number of bytes to read. If null, just return the handle.
354 * Maintenance::STDIN_ALL returns the full length
357 protected function getStdin( $len = null ) {
358 if ( $len == self
::STDIN_ALL
) {
359 return file_get_contents( 'php://stdin' );
361 $f = fopen( 'php://stdin', 'rt' );
365 $input = fgets( $f, $len );
368 return rtrim( $input );
374 public function isQuiet() {
375 return $this->mQuiet
;
379 * Throw some output to the user. Scripts can call this with no fears,
380 * as we handle all --quiet stuff here
381 * @param string $out The text to show to the user
382 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
384 protected function output( $out, $channel = null ) {
385 // This is sometimes called very early, before Setup.php is included.
386 if ( class_exists( MediaWikiServices
::class ) ) {
387 // Try to periodically flush buffered metrics to avoid OOMs
388 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
389 if ( $stats->getDataCount() > 1000 ) {
390 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
394 if ( $this->mQuiet
) {
397 if ( $channel === null ) {
398 $this->cleanupChanneled();
401 $out = preg_replace( '/\n\z/', '', $out );
402 $this->outputChanneled( $out, $channel );
407 * Throw an error to the user. Doesn't respect --quiet, so don't use
408 * this for non-error output
409 * @param string $err The error to display
410 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
412 protected function error( $err, $die = 0 ) {
413 if ( intval( $die ) !== 0 ) {
414 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
415 $this->fatalError( $err, intval( $die ) );
417 $this->outputChanneled( false );
419 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
420 !defined( 'MW_PHPUNIT_TEST' )
422 fwrite( STDERR
, $err . "\n" );
429 * Output a message and terminate the current script.
431 * @param string $msg Error message
432 * @param int $exitCode PHP exit status. Should be in range 1-254.
435 protected function fatalError( $msg, $exitCode = 1 ) {
436 $this->error( $msg );
440 private $atLineStart = true;
441 private $lastChannel = null;
444 * Clean up channeled output. Output a newline if necessary.
446 public function cleanupChanneled() {
447 if ( !$this->atLineStart
) {
449 $this->atLineStart
= true;
454 * Message outputter with channeled message support. Messages on the
455 * same channel are concatenated, but any intervening messages in another
456 * channel start a new line.
457 * @param string $msg The message without trailing newline
458 * @param string $channel Channel identifier or null for no
459 * channel. Channel comparison uses ===.
461 public function outputChanneled( $msg, $channel = null ) {
462 if ( $msg === false ) {
463 $this->cleanupChanneled();
468 // End the current line if necessary
469 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
475 $this->atLineStart
= false;
476 if ( $channel === null ) {
477 // For unchanneled messages, output trailing newline immediately
479 $this->atLineStart
= true;
481 $this->lastChannel
= $channel;
485 * Does the script need different DB access? By default, we give Maintenance
486 * scripts normal rights to the DB. Sometimes, a script needs admin rights
487 * access for a reason and sometimes they want no access. Subclasses should
488 * override and return one of the following values, as needed:
489 * Maintenance::DB_NONE - For no DB access at all
490 * Maintenance::DB_STD - For normal DB access, default
491 * Maintenance::DB_ADMIN - For admin DB access
494 public function getDbType() {
499 * Add the default parameters to the scripts
501 protected function addDefaultParams() {
502 # Generic (non script dependant) options:
504 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
505 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
506 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
507 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
508 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
511 'Set a specific memory limit for the script, '
512 . '"max" for no limit or "default" to avoid changing it',
516 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
517 "http://en.wikipedia.org. This is sometimes necessary because " .
518 "server name detection may fail in command line scripts.", false, true );
519 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
520 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
521 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
523 # Save generic options to display them separately in help
524 $this->mGenericParameters
= $this->mParams
;
526 # Script dependant options:
528 // If we support a DB, show the options
529 if ( $this->getDbType() > 0 ) {
530 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
531 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
534 # Save additional script dependant options to display
535 # Â them separately in help
536 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
543 public function getConfig() {
544 if ( $this->config
=== null ) {
545 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
548 return $this->config
;
553 * @param Config $config
555 public function setConfig( Config
$config ) {
556 $this->config
= $config;
560 * Indicate that the specified extension must be
561 * loaded before the script can run.
563 * This *must* be called in the constructor.
566 * @param string $name
568 protected function requireExtension( $name ) {
569 $this->requiredExtensions
[] = $name;
573 * Verify that the required extensions are installed
577 public function checkRequiredExtensions() {
578 $registry = ExtensionRegistry
::getInstance();
580 foreach ( $this->requiredExtensions
as $name ) {
581 if ( !$registry->isLoaded( $name ) ) {
587 $joined = implode( ', ', $missing );
588 $msg = "The following extensions are required to be installed "
589 . "for this script to run: $joined. Please enable them and then try again.";
590 $this->fatalError( $msg );
595 * Set triggers like when to try to run deferred updates
598 public function setAgentAndTriggers() {
599 if ( function_exists( 'posix_getpwuid' ) ) {
600 $agent = posix_getpwuid( posix_geteuid() )['name'];
604 $agent .= '@' . wfHostname();
606 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
607 // Add a comment for easy SHOW PROCESSLIST interpretation
608 $lbFactory->setAgentName(
609 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
611 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
615 * @param LBFactory $LBFactory
616 * @param Config $config
619 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
620 $services = MediaWikiServices
::getInstance();
621 $stats = $services->getStatsdDataFactory();
622 // Hook into period lag checks which often happen in long-running scripts
623 $lbFactory = $services->getDBLoadBalancerFactory();
624 $lbFactory->setWaitForReplicationListener(
626 function () use ( $stats, $config ) {
627 // Check config in case of JobRunner and unit tests
628 if ( $config->get( 'CommandLineMode' ) ) {
629 DeferredUpdates
::tryOpportunisticExecute( 'run' );
631 // Try to periodically flush buffered metrics to avoid OOMs
632 MediaWiki
::emitBufferedStatsdData( $stats, $config );
635 // Check for other windows to run them. A script may read or do a few writes
636 // to the master but mostly be writing to something else, like a file store.
637 $lbFactory->getMainLB()->setTransactionListener(
639 function ( $trigger ) use ( $stats, $config ) {
640 // Check config in case of JobRunner and unit tests
641 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
642 DeferredUpdates
::tryOpportunisticExecute( 'run' );
644 // Try to periodically flush buffered metrics to avoid OOMs
645 MediaWiki
::emitBufferedStatsdData( $stats, $config );
651 * Run a child maintenance script. Pass all of the current arguments
653 * @param string $maintClass A name of a child maintenance class
654 * @param string $classFile Full path of where the child is
655 * @return Maintenance
657 public function runChild( $maintClass, $classFile = null ) {
658 // Make sure the class is loaded first
659 if ( !class_exists( $maintClass ) ) {
661 require_once $classFile;
663 if ( !class_exists( $maintClass ) ) {
664 $this->error( "Cannot spawn child: $maintClass" );
669 * @var $child Maintenance
671 $child = new $maintClass();
672 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
673 if ( !is_null( $this->mDb
) ) {
674 $child->setDB( $this->mDb
);
681 * Do some sanity checking and basic setup
683 public function setup() {
684 global $IP, $wgCommandLineMode;
686 # Abort if called from a web server
687 # wfIsCLI() is not available yet
688 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
689 $this->fatalError( 'This script must be run from the command line' );
692 if ( $IP === null ) {
693 $this->fatalError( "\$IP not set, aborting!\n" .
694 '(Did you forget to call parent::__construct() in your maintenance script?)' );
697 # Make sure we can handle script parameters
698 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
699 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
702 // Send PHP warnings and errors to stderr instead of stdout.
703 // This aids in diagnosing problems, while keeping messages
704 // out of redirected output.
705 if ( ini_get( 'display_errors' ) ) {
706 ini_set( 'display_errors', 'stderr' );
709 $this->loadParamsAndArgs();
712 # Set the memory limit
713 # Note we need to set it again later in cache LocalSettings changed it
714 $this->adjustMemoryLimit();
716 # Set max execution time to 0 (no limit). PHP.net says that
717 # "When running PHP from the command line the default setting is 0."
718 # But sometimes this doesn't seem to be the case.
719 ini_set( 'max_execution_time', 0 );
721 # Define us as being in MediaWiki
722 define( 'MEDIAWIKI', true );
724 $wgCommandLineMode = true;
726 # Turn off output buffering if it's on
727 while ( ob_get_level() > 0 ) {
731 $this->validateParamsAndArgs();
735 * Normally we disable the memory_limit when running admin scripts.
736 * Some scripts may wish to actually set a limit, however, to avoid
737 * blowing up unexpectedly. We also support a --memory-limit option,
738 * to allow sysadmins to explicitly set one if they'd prefer to override
739 * defaults (or for people using Suhosin which yells at you for trying
740 * to disable the limits)
743 public function memoryLimit() {
744 $limit = $this->getOption( 'memory-limit', 'max' );
745 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
750 * Adjusts PHP's memory limit to better suit our needs, if needed.
752 protected function adjustMemoryLimit() {
753 $limit = $this->memoryLimit();
754 if ( $limit == 'max' ) {
755 $limit = -1; // no memory limit
757 if ( $limit != 'default' ) {
758 ini_set( 'memory_limit', $limit );
763 * Activate the profiler (assuming $wgProfiler is set)
765 protected function activateProfiler() {
766 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
768 $output = $this->getOption( 'profiler' );
773 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
774 $class = $wgProfiler['class'];
775 /** @var Profiler $profiler */
776 $profiler = new $class(
777 [ 'sampling' => 1, 'output' => [ $output ] ]
779 +
[ 'threshold' => $wgProfileLimit ]
781 $profiler->setTemplated( true );
782 Profiler
::replaceStubInstance( $profiler );
785 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
786 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
787 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
791 * Clear all params and arguments.
793 public function clearParamsAndArgs() {
794 $this->mOptions
= [];
796 $this->mInputLoaded
= false;
800 * Load params and arguments from a given array
801 * of command-line arguments
806 public function loadWithArgv( $argv ) {
809 $this->orderedOptions
= [];
812 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
813 if ( $arg == '--' ) {
814 # End of options, remainder should be considered arguments
815 $arg = next( $argv );
816 while ( $arg !== false ) {
818 $arg = next( $argv );
821 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
823 $option = substr( $arg, 2 );
824 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
825 $param = next( $argv );
826 if ( $param === false ) {
827 $this->error( "\nERROR: $option parameter needs a value after it\n" );
828 $this->maybeHelp( true );
831 $this->setParam( $options, $option, $param );
833 $bits = explode( '=', $option, 2 );
834 if ( count( $bits ) > 1 ) {
841 $this->setParam( $options, $option, $param );
843 } elseif ( $arg == '-' ) {
844 # Lonely "-", often used to indicate stdin or stdout.
846 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
848 $argLength = strlen( $arg );
849 for ( $p = 1; $p < $argLength; $p++
) {
851 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
852 $option = $this->mShortParamsMap
[$option];
855 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
856 $param = next( $argv );
857 if ( $param === false ) {
858 $this->error( "\nERROR: $option parameter needs a value after it\n" );
859 $this->maybeHelp( true );
861 $this->setParam( $options, $option, $param );
863 $this->setParam( $options, $option, 1 );
871 $this->mOptions
= $options;
872 $this->mArgs
= $args;
873 $this->loadSpecialVars();
874 $this->mInputLoaded
= true;
878 * Helper function used solely by loadParamsAndArgs
879 * to prevent code duplication
881 * This sets the param in the options array based on
882 * whether or not it can be specified multiple times.
885 * @param array $options
886 * @param string $option
887 * @param mixed $value
889 private function setParam( &$options, $option, $value ) {
890 $this->orderedOptions
[] = [ $option, $value ];
892 if ( isset( $this->mParams
[$option] ) ) {
893 $multi = $this->mParams
[$option]['multiOccurrence'];
897 $exists = array_key_exists( $option, $options );
898 if ( $multi && $exists ) {
899 $options[$option][] = $value;
900 } elseif ( $multi ) {
901 $options[$option] = [ $value ];
902 } elseif ( !$exists ) {
903 $options[$option] = $value;
905 $this->error( "\nERROR: $option parameter given twice\n" );
906 $this->maybeHelp( true );
911 * Process command line arguments
912 * $mOptions becomes an array with keys set to the option names
913 * $mArgs becomes a zero-based array containing the non-option arguments
915 * @param string $self The name of the script, if any
916 * @param array $opts An array of options, in form of key=>value
917 * @param array $args An array of command line arguments
919 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
920 # If we were given opts or args, set those and return early
922 $this->mSelf
= $self;
923 $this->mInputLoaded
= true;
926 $this->mOptions
= $opts;
927 $this->mInputLoaded
= true;
930 $this->mArgs
= $args;
931 $this->mInputLoaded
= true;
934 # If we've already loaded input (either by user values or from $argv)
935 # skip on loading it again. The array_shift() will corrupt values if
936 # it's run again and again
937 if ( $this->mInputLoaded
) {
938 $this->loadSpecialVars();
944 $this->mSelf
= $argv[0];
945 $this->loadWithArgv( array_slice( $argv, 1 ) );
949 * Run some validation checks on the params, etc
951 protected function validateParamsAndArgs() {
953 # Check to make sure we've got all the required options
954 foreach ( $this->mParams
as $opt => $info ) {
955 if ( $info['require'] && !$this->hasOption( $opt ) ) {
956 $this->error( "Param $opt required!" );
961 foreach ( $this->mArgList
as $k => $info ) {
962 if ( $info['require'] && !$this->hasArg( $k ) ) {
963 $this->error( 'Argument <' . $info['name'] . '> required!' );
969 $this->maybeHelp( true );
974 * Handle the special variables that are global to all scripts
976 protected function loadSpecialVars() {
977 if ( $this->hasOption( 'dbuser' ) ) {
978 $this->mDbUser
= $this->getOption( 'dbuser' );
980 if ( $this->hasOption( 'dbpass' ) ) {
981 $this->mDbPass
= $this->getOption( 'dbpass' );
983 if ( $this->hasOption( 'quiet' ) ) {
984 $this->mQuiet
= true;
986 if ( $this->hasOption( 'batch-size' ) ) {
987 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
992 * Maybe show the help.
993 * @param bool $force Whether to force the help to show, default false
995 protected function maybeHelp( $force = false ) {
996 if ( !$force && !$this->hasOption( 'help' ) ) {
1000 $screenWidth = 80; // TODO: Calculate this!
1002 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1004 ksort( $this->mParams
);
1005 $this->mQuiet
= false;
1008 if ( $this->mDescription
) {
1009 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1011 $output = "\nUsage: php " . basename( $this->mSelf
);
1013 // ... append parameters ...
1014 if ( $this->mParams
) {
1015 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1018 // ... and append arguments.
1019 if ( $this->mArgList
) {
1021 foreach ( $this->mArgList
as $k => $arg ) {
1022 if ( $arg['require'] ) {
1023 $output .= '<' . $arg['name'] . '>';
1025 $output .= '[' . $arg['name'] . ']';
1027 if ( $k < count( $this->mArgList
) - 1 ) {
1032 $this->output( "$output\n\n" );
1034 # TODO abstract some repetitive code below
1036 // Generic parameters
1037 $this->output( "Generic maintenance parameters:\n" );
1038 foreach ( $this->mGenericParameters
as $par => $info ) {
1039 if ( $info['shortName'] !== false ) {
1040 $par .= " (-{$info['shortName']})";
1043 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1044 "\n$tab$tab" ) . "\n"
1047 $this->output( "\n" );
1049 $scriptDependantParams = $this->mDependantParameters
;
1050 if ( count( $scriptDependantParams ) > 0 ) {
1051 $this->output( "Script dependant parameters:\n" );
1052 // Parameters description
1053 foreach ( $scriptDependantParams as $par => $info ) {
1054 if ( $info['shortName'] !== false ) {
1055 $par .= " (-{$info['shortName']})";
1058 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1059 "\n$tab$tab" ) . "\n"
1062 $this->output( "\n" );
1065 // Script specific parameters not defined on construction by
1066 // Maintenance::addDefaultParams()
1067 $scriptSpecificParams = array_diff_key(
1068 # all script parameters:
1070 # remove the Maintenance default parameters:
1071 $this->mGenericParameters
,
1072 $this->mDependantParameters
1074 if ( count( $scriptSpecificParams ) > 0 ) {
1075 $this->output( "Script specific parameters:\n" );
1076 // Parameters description
1077 foreach ( $scriptSpecificParams as $par => $info ) {
1078 if ( $info['shortName'] !== false ) {
1079 $par .= " (-{$info['shortName']})";
1082 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1083 "\n$tab$tab" ) . "\n"
1086 $this->output( "\n" );
1090 if ( count( $this->mArgList
) > 0 ) {
1091 $this->output( "Arguments:\n" );
1092 // Arguments description
1093 foreach ( $this->mArgList
as $info ) {
1094 $openChar = $info['require'] ?
'<' : '[';
1095 $closeChar = $info['require'] ?
'>' : ']';
1097 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1098 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1101 $this->output( "\n" );
1108 * Handle some last-minute setup here.
1110 public function finalSetup() {
1111 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1112 global $wgDBadminuser, $wgDBadminpassword;
1113 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1115 # Turn off output buffering again, it might have been turned on in the settings files
1116 if ( ob_get_level() ) {
1120 $wgCommandLineMode = true;
1122 # Override $wgServer
1123 if ( $this->hasOption( 'server' ) ) {
1124 $wgServer = $this->getOption( 'server', $wgServer );
1127 # If these were passed, use them
1128 if ( $this->mDbUser
) {
1129 $wgDBadminuser = $this->mDbUser
;
1131 if ( $this->mDbPass
) {
1132 $wgDBadminpassword = $this->mDbPass
;
1135 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1136 $wgDBuser = $wgDBadminuser;
1137 $wgDBpassword = $wgDBadminpassword;
1139 if ( $wgDBservers ) {
1141 * @var $wgDBservers array
1143 foreach ( $wgDBservers as $i => $server ) {
1144 $wgDBservers[$i]['user'] = $wgDBuser;
1145 $wgDBservers[$i]['password'] = $wgDBpassword;
1148 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1149 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1150 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1152 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1155 # Apply debug settings
1156 if ( $this->hasOption( 'mwdebug' ) ) {
1157 require __DIR__
. '/../includes/DevelopmentSettings.php';
1160 // Per-script profiling; useful for debugging
1161 $this->activateProfiler();
1163 $this->afterFinalSetup();
1165 $wgShowSQLErrors = true;
1167 Wikimedia\
suppressWarnings();
1168 set_time_limit( 0 );
1169 Wikimedia\restoreWarnings
();
1171 $this->adjustMemoryLimit();
1175 * Execute a callback function at the end of initialisation
1177 protected function afterFinalSetup() {
1178 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1179 call_user_func( MW_CMDLINE_CALLBACK
);
1184 * Potentially debug globals. Originally a feature only
1187 public function globals() {
1188 if ( $this->hasOption( 'globals' ) ) {
1189 print_r( $GLOBALS );
1194 * Generic setup for most installs. Returns the location of LocalSettings
1197 public function loadSettings() {
1198 global $wgCommandLineMode, $IP;
1200 if ( isset( $this->mOptions
['conf'] ) ) {
1201 $settingsFile = $this->mOptions
['conf'];
1202 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1203 $settingsFile = MW_CONFIG_FILE
;
1205 $settingsFile = "$IP/LocalSettings.php";
1207 if ( isset( $this->mOptions
['wiki'] ) ) {
1208 $bits = explode( '-', $this->mOptions
['wiki'] );
1209 if ( count( $bits ) == 1 ) {
1212 define( 'MW_DB', $bits[0] );
1213 define( 'MW_PREFIX', $bits[1] );
1216 if ( !is_readable( $settingsFile ) ) {
1217 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1218 "must exist and be readable in the source directory.\n" .
1219 "Use --conf to specify it." );
1221 if ( isset( $this->mOptions
['server'] ) ) {
1222 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1224 $wgCommandLineMode = true;
1226 return $settingsFile;
1230 * Support function for cleaning up redundant text records
1231 * @param bool $delete Whether or not to actually delete the records
1232 * @author Rob Church <robchur@gmail.com>
1234 public function purgeRedundantText( $delete = true ) {
1235 # Data should come off the master, wrapped in a transaction
1236 $dbw = $this->getDB( DB_MASTER
);
1237 $this->beginTransaction( $dbw, __METHOD__
);
1239 # Get "active" text records from the revisions table
1241 $this->output( 'Searching for active text records in revisions table...' );
1242 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1243 foreach ( $res as $row ) {
1244 $cur[] = $row->rev_text_id
;
1246 $this->output( "done.\n" );
1248 # Get "active" text records from the archive table
1249 $this->output( 'Searching for active text records in archive table...' );
1250 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1251 foreach ( $res as $row ) {
1252 # old pre-MW 1.5 records can have null ar_text_id's.
1253 if ( $row->ar_text_id
!== null ) {
1254 $cur[] = $row->ar_text_id
;
1257 $this->output( "done.\n" );
1259 # Get the IDs of all text records not in these sets
1260 $this->output( 'Searching for inactive text records...' );
1261 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1262 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1264 foreach ( $res as $row ) {
1265 $old[] = $row->old_id
;
1267 $this->output( "done.\n" );
1269 # Inform the user of what we're going to do
1270 $count = count( $old );
1271 $this->output( "$count inactive items found.\n" );
1273 # Delete as appropriate
1274 if ( $delete && $count ) {
1275 $this->output( 'Deleting...' );
1276 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1277 $this->output( "done.\n" );
1281 $this->commitTransaction( $dbw, __METHOD__
);
1285 * Get the maintenance directory.
1288 protected function getDir() {
1293 * Returns a database to be used by current maintenance script. It can be set by setDB().
1294 * If not set, wfGetDB() will be used.
1295 * This function has the same parameters as wfGetDB()
1297 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1298 * @param string|string[] $groups default: empty array
1299 * @param string|bool $wiki default: current wiki
1300 * @return IMaintainableDatabase
1302 protected function getDB( $db, $groups = [], $wiki = false ) {
1303 if ( is_null( $this->mDb
) ) {
1304 return wfGetDB( $db, $groups, $wiki );
1311 * Sets database object to be returned by getDB().
1313 * @param IDatabase $db
1315 public function setDB( IDatabase
$db ) {
1320 * Begin a transcation on a DB
1322 * This method makes it clear that begin() is called from a maintenance script,
1323 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1325 * @param IDatabase $dbw
1326 * @param string $fname Caller name
1329 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1330 $dbw->begin( $fname );
1334 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1336 * This method makes it clear that commit() is called from a maintenance script,
1337 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1339 * @param IDatabase $dbw
1340 * @param string $fname Caller name
1341 * @return bool Whether the replica DB wait succeeded
1344 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1345 $dbw->commit( $fname );
1347 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1348 $lbFactory->waitForReplication(
1349 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1351 $this->lastReplicationWait
= microtime( true );
1354 } catch ( DBReplicationWaitError
$e ) {
1360 * Rollback the transcation on a DB handle
1362 * This method makes it clear that rollback() is called from a maintenance script,
1363 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1365 * @param IDatabase $dbw
1366 * @param string $fname Caller name
1369 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1370 $dbw->rollback( $fname );
1374 * Lock the search index
1375 * @param IMaintainableDatabase &$db
1377 private function lockSearchindex( $db ) {
1378 $write = [ 'searchindex' ];
1388 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1393 * @param IMaintainableDatabase &$db
1395 private function unlockSearchindex( $db ) {
1396 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1400 * Unlock and lock again
1401 * Since the lock is low-priority, queued reads will be able to complete
1402 * @param IMaintainableDatabase &$db
1404 private function relockSearchindex( $db ) {
1405 $this->unlockSearchindex( $db );
1406 $this->lockSearchindex( $db );
1410 * Perform a search index update with locking
1411 * @param int $maxLockTime The maximum time to keep the search index locked.
1412 * @param string $callback The function that will update the function.
1413 * @param IMaintainableDatabase $dbw
1414 * @param array $results
1416 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1420 if ( $maxLockTime ) {
1421 $this->output( " --- Waiting for lock ---" );
1422 $this->lockSearchindex( $dbw );
1424 $this->output( "\n" );
1427 # Loop through the results and do a search update
1428 foreach ( $results as $row ) {
1429 # Allow reads to be processed
1430 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1431 $this->output( " --- Relocking ---" );
1432 $this->relockSearchindex( $dbw );
1434 $this->output( "\n" );
1436 call_user_func( $callback, $dbw, $row );
1439 # Unlock searchindex
1440 if ( $maxLockTime ) {
1441 $this->output( " --- Unlocking --" );
1442 $this->unlockSearchindex( $dbw );
1443 $this->output( "\n" );
1448 * Update the searchindex table for a given pageid
1449 * @param IDatabase $dbw A database write handle
1450 * @param int $pageId The page ID to update.
1451 * @return null|string
1453 public function updateSearchIndexForPage( $dbw, $pageId ) {
1454 // Get current revision
1455 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1458 $titleObj = $rev->getTitle();
1459 $title = $titleObj->getPrefixedDBkey();
1460 $this->output( "$title..." );
1461 # Update searchindex
1462 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1464 $this->output( "\n" );
1471 * Count down from $seconds to zero on the terminal, with a one-second pause
1472 * between showing each number. If the maintenance script is in quiet mode,
1473 * this function does nothing.
1477 * @codeCoverageIgnore
1478 * @param int $seconds
1480 protected function countDown( $seconds ) {
1481 if ( $this->isQuiet() ) {
1484 for ( $i = $seconds; $i >= 0; $i-- ) {
1485 if ( $i != $seconds ) {
1486 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1488 $this->output( $i );
1493 $this->output( "\n" );
1497 * Wrapper for posix_isatty()
1498 * We default as considering stdin a tty (for nice readline methods)
1499 * but treating stout as not a tty to avoid color codes
1501 * @param mixed $fd File descriptor
1504 public static function posix_isatty( $fd ) {
1505 if ( !function_exists( 'posix_isatty' ) ) {
1508 return posix_isatty( $fd );
1513 * Prompt the console for input
1514 * @param string $prompt What to begin the line with, like '> '
1515 * @return string Response
1517 public static function readconsole( $prompt = '> ' ) {
1518 static $isatty = null;
1519 if ( is_null( $isatty ) ) {
1520 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1523 if ( $isatty && function_exists( 'readline' ) ) {
1524 return readline( $prompt );
1527 $st = self
::readlineEmulation( $prompt );
1529 if ( feof( STDIN
) ) {
1532 $st = fgets( STDIN
, 1024 );
1535 if ( $st === false ) {
1538 $resp = trim( $st );
1545 * Emulate readline()
1546 * @param string $prompt What to begin the line with, like '> '
1549 private static function readlineEmulation( $prompt ) {
1550 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1551 if ( !wfIsWindows() && $bash ) {
1553 $encPrompt = wfEscapeShellArg( $prompt );
1554 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1555 $encCommand = wfEscapeShellArg( $command );
1556 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1558 if ( $retval == 0 ) {
1560 } elseif ( $retval == 127 ) {
1561 // Couldn't execute bash even though we thought we saw it.
1562 // Shell probably spit out an error message, sorry :(
1563 // Fall through to fgets()...
1570 // Fallback... we'll have no editing controls, EWWW
1571 if ( feof( STDIN
) ) {
1576 return fgets( STDIN
, 1024 );
1580 * Get the terminal size as a two-element array where the first element
1581 * is the width (number of columns) and the second element is the height
1586 public static function getTermSize() {
1587 $default = [ 80, 50 ];
1588 if ( wfIsWindows() ) {
1591 // It's possible to get the screen size with VT-100 terminal escapes,
1592 // but reading the responses is not possible without setting raw mode
1593 // (unless you want to require the user to press enter), and that
1594 // requires an ioctl(), which we can't do. So we have to shell out to
1595 // something that can do the relevant syscalls. There are a few
1596 // options. Linux and Mac OS X both have "stty size" which does the
1598 $result = Shell
::command( 'stty', 'size' )
1600 if ( $result->getExitCode() !== 0 ) {
1603 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1606 return [ intval( $m[2] ), intval( $m[1] ) ];
1610 * Call this to set up the autoloader to allow classes to be used from the
1613 public static function requireTestsAutoloader() {
1614 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1619 * Fake maintenance wrapper, mostly used for the web installer/updater
1621 class FakeMaintenance
extends Maintenance
{
1622 protected $mSelf = "FakeMaintenanceScript";
1624 public function execute() {
1630 * Class for scripts that perform database maintenance and want to log the
1631 * update in `updatelog` so we can later skip it
1633 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1634 public function __construct() {
1635 parent
::__construct();
1636 $this->addOption( 'force', 'Run the update even if it was completed already' );
1637 $this->setBatchSize( 200 );
1640 public function execute() {
1641 $db = $this->getDB( DB_MASTER
);
1642 $key = $this->getUpdateKey();
1644 if ( !$this->hasOption( 'force' )
1645 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1647 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1652 if ( !$this->doDBUpdates() ) {
1656 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1659 $this->output( $this->updatelogFailedMessage() . "\n" );
1666 * Message to show that the update was done already and was just skipped
1669 protected function updateSkippedMessage() {
1670 $key = $this->getUpdateKey();
1672 return "Update '{$key}' already logged as completed.";
1676 * Message to show that the update log was unable to log the completion of this update
1679 protected function updatelogFailedMessage() {
1680 $key = $this->getUpdateKey();
1682 return "Unable to log update '{$key}' as completed.";
1686 * Do the actual work. All child classes will need to implement this.
1687 * Return true to log the update as done or false (usually on failure).
1690 abstract protected function doDBUpdates();
1693 * Get the update key name to go in the update log table
1696 abstract protected function getUpdateKey();