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' );
40 * @deprecated since 1.31
42 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
46 use Wikimedia\Rdbms\IDatabase
;
47 use MediaWiki\Logger\LoggerFactory
;
48 use MediaWiki\MediaWikiServices
;
49 use Wikimedia\Rdbms\LBFactory
;
50 use Wikimedia\Rdbms\IMaintainableDatabase
;
53 * Abstract maintenance class for quickly writing and churning out
54 * maintenance scripts with minimal effort. All that _must_ be defined
55 * is the execute() method. See docs/maintenance.txt for more info
56 * and a quick demo of how to use it.
59 * @ingroup Maintenance
61 abstract class Maintenance
{
63 * Constants for DB access type
64 * @see Maintenance::getDbType()
70 // Const for getStdin()
71 const STDIN_ALL
= 'all';
73 // This is the desired params
74 protected $mParams = [];
76 // Array of mapping short parameters to long ones
77 protected $mShortParamsMap = [];
79 // Array of desired args
80 protected $mArgList = [];
82 // This is the list of options that were actually passed
83 protected $mOptions = [];
85 // This is the list of arguments that were actually passed
86 protected $mArgs = [];
88 // Name of the script currently running
91 // Special vars for params that are always used
92 protected $mQuiet = false;
93 protected $mDbUser, $mDbPass;
95 // A description of the script, children should change this via addDescription()
96 protected $mDescription = '';
98 // Have we already loaded our user input?
99 protected $mInputLoaded = false;
102 * Batch size. If a script supports this, they should set
103 * a default with setBatchSize()
107 protected $mBatchSize = null;
109 // Generic options added by addDefaultParams()
110 private $mGenericParameters = [];
111 // Generic options which might or not be supported by the script
112 private $mDependantParameters = [];
115 * Used by getDB() / setDB()
116 * @var IMaintainableDatabase
120 /** @var float UNIX timestamp */
121 private $lastReplicationWait = 0.0;
124 * Used when creating separate schema files.
130 * Accessible via getConfig()
137 * @see Maintenance::requireExtension
140 private $requiredExtensions = [];
143 * Used to read the options in the order they were passed.
144 * Useful for option chaining (Ex. dumpBackup.php). It will
145 * be an empty array if the options are passed in through
146 * loadParamsAndArgs( $self, $opts, $args ).
148 * This is an array of arrays where
149 * 0 => the option and 1 => parameter value.
153 public $orderedOptions = [];
156 * Default constructor. Children should call this *first* if implementing
157 * their own constructors
159 public function __construct() {
160 // Setup $IP, using MW_INSTALL_PATH if it exists
162 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
163 ?
getenv( 'MW_INSTALL_PATH' )
164 : realpath( __DIR__
. '/..' );
166 $this->addDefaultParams();
167 register_shutdown_function( [ $this, 'outputChanneled' ], false );
171 * Should we execute the maintenance script, or just allow it to be included
172 * as a standalone class? It checks that the call stack only includes this
173 * function and "requires" (meaning was called from the file scope)
177 public static function shouldExecute() {
178 global $wgCommandLineMode;
180 if ( !function_exists( 'debug_backtrace' ) ) {
181 // If someone has a better idea...
182 return $wgCommandLineMode;
185 $bt = debug_backtrace();
186 $count = count( $bt );
188 return false; // sanity
190 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
191 return false; // last call should be to this function
193 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
194 for ( $i = 1; $i < $count; $i++
) {
195 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
196 return false; // previous calls should all be "requires"
204 * Do the actual work. All child classes will need to implement this
206 * @return bool|null True for success, false for failure. Not returning
207 * a value, or returning null, is also interpreted as success. Returning
208 * false for failure will cause doMaintenance.php to exit the process
209 * with a non-zero exit status.
211 abstract public function execute();
214 * Add a parameter to the script. Will be displayed on --help
215 * with the associated description
217 * @param string $name The name of the param (help, version, etc)
218 * @param string $description The description of the param to show on --help
219 * @param bool $required Is the param required?
220 * @param bool $withArg Is an argument required with this option?
221 * @param string|bool $shortName Character to use as short name
222 * @param bool $multiOccurrence Can this option be passed multiple times?
224 protected function addOption( $name, $description, $required = false,
225 $withArg = false, $shortName = false, $multiOccurrence = false
227 $this->mParams
[$name] = [
228 'desc' => $description,
229 'require' => $required,
230 'withArg' => $withArg,
231 'shortName' => $shortName,
232 'multiOccurrence' => $multiOccurrence
235 if ( $shortName !== false ) {
236 $this->mShortParamsMap
[$shortName] = $name;
241 * Checks to see if a particular param exists.
242 * @param string $name The name of the param
245 protected function hasOption( $name ) {
246 return isset( $this->mOptions
[$name] );
250 * Get an option, or return the default.
252 * If the option was added to support multiple occurrences,
253 * this will return an array.
255 * @param string $name The name of the param
256 * @param mixed $default Anything you want, default null
259 protected function getOption( $name, $default = null ) {
260 if ( $this->hasOption( $name ) ) {
261 return $this->mOptions
[$name];
263 // Set it so we don't have to provide the default again
264 $this->mOptions
[$name] = $default;
266 return $this->mOptions
[$name];
271 * Add some args that are needed
272 * @param string $arg Name of the arg, like 'start'
273 * @param string $description Short description of the arg
274 * @param bool $required Is this required?
276 protected function addArg( $arg, $description, $required = true ) {
277 $this->mArgList
[] = [
279 'desc' => $description,
280 'require' => $required
285 * Remove an option. Useful for removing options that won't be used in your script.
286 * @param string $name The option to remove.
288 protected function deleteOption( $name ) {
289 unset( $this->mParams
[$name] );
293 * Set the description text.
294 * @param string $text The text of the description
296 protected function addDescription( $text ) {
297 $this->mDescription
= $text;
301 * Does a given argument exist?
302 * @param int $argId The integer value (from zero) for the arg
305 protected function hasArg( $argId = 0 ) {
306 return isset( $this->mArgs
[$argId] );
311 * @param int $argId The integer value (from zero) for the arg
312 * @param mixed $default The default if it doesn't exist
315 protected function getArg( $argId = 0, $default = null ) {
316 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
326 protected function getBatchSize() {
327 return $this->mBatchSize
;
331 * Set the batch size.
332 * @param int $s The number of operations to do in a batch
334 protected function setBatchSize( $s = 0 ) {
335 $this->mBatchSize
= $s;
337 // If we support $mBatchSize, show the option.
338 // Used to be in addDefaultParams, but in order for that to
339 // work, subclasses would have to call this function in the constructor
340 // before they called parent::__construct which is just weird
341 // (and really wasn't done).
342 if ( $this->mBatchSize
) {
343 $this->addOption( 'batch-size', 'Run this many operations ' .
344 'per batch, default: ' . $this->mBatchSize
, false, true );
345 if ( isset( $this->mParams
['batch-size'] ) ) {
346 // This seems a little ugly...
347 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
353 * Get the script's name
356 public function getName() {
361 * Return input from stdin.
362 * @param int $len The number of bytes to read. If null, just return the handle.
363 * Maintenance::STDIN_ALL returns the full length
366 protected function getStdin( $len = null ) {
367 if ( $len == self
::STDIN_ALL
) {
368 return file_get_contents( 'php://stdin' );
370 $f = fopen( 'php://stdin', 'rt' );
374 $input = fgets( $f, $len );
377 return rtrim( $input );
383 public function isQuiet() {
384 return $this->mQuiet
;
388 * Throw some output to the user. Scripts can call this with no fears,
389 * as we handle all --quiet stuff here
390 * @param string $out The text to show to the user
391 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
393 protected function output( $out, $channel = null ) {
394 // This is sometimes called very early, before Setup.php is included.
395 if ( class_exists( MediaWikiServices
::class ) ) {
396 // Try to periodically flush buffered metrics to avoid OOMs
397 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
398 if ( $stats->getDataCount() > 1000 ) {
399 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
403 if ( $this->mQuiet
) {
406 if ( $channel === null ) {
407 $this->cleanupChanneled();
410 $out = preg_replace( '/\n\z/', '', $out );
411 $this->outputChanneled( $out, $channel );
416 * Throw an error to the user. Doesn't respect --quiet, so don't use
417 * this for non-error output
418 * @param string $err The error to display
419 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
421 protected function error( $err, $die = 0 ) {
422 if ( intval( $die ) !== 0 ) {
423 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
424 $this->fatalError( $err, intval( $die ) );
426 $this->outputChanneled( false );
428 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
429 !defined( 'MW_PHPUNIT_TEST' )
431 fwrite( STDERR
, $err . "\n" );
438 * Output a message and terminate the current script.
440 * @param string $msg Error message
441 * @param int $exitCode PHP exit status. Should be in range 1-254.
444 protected function fatalError( $msg, $exitCode = 1 ) {
445 $this->error( $msg );
449 private $atLineStart = true;
450 private $lastChannel = null;
453 * Clean up channeled output. Output a newline if necessary.
455 public function cleanupChanneled() {
456 if ( !$this->atLineStart
) {
458 $this->atLineStart
= true;
463 * Message outputter with channeled message support. Messages on the
464 * same channel are concatenated, but any intervening messages in another
465 * channel start a new line.
466 * @param string $msg The message without trailing newline
467 * @param string $channel Channel identifier or null for no
468 * channel. Channel comparison uses ===.
470 public function outputChanneled( $msg, $channel = null ) {
471 if ( $msg === false ) {
472 $this->cleanupChanneled();
477 // End the current line if necessary
478 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
484 $this->atLineStart
= false;
485 if ( $channel === null ) {
486 // For unchanneled messages, output trailing newline immediately
488 $this->atLineStart
= true;
490 $this->lastChannel
= $channel;
494 * Does the script need different DB access? By default, we give Maintenance
495 * scripts normal rights to the DB. Sometimes, a script needs admin rights
496 * access for a reason and sometimes they want no access. Subclasses should
497 * override and return one of the following values, as needed:
498 * Maintenance::DB_NONE - For no DB access at all
499 * Maintenance::DB_STD - For normal DB access, default
500 * Maintenance::DB_ADMIN - For admin DB access
503 public function getDbType() {
508 * Add the default parameters to the scripts
510 protected function addDefaultParams() {
511 # Generic (non script dependant) options:
513 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
514 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
515 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
516 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
517 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
520 'Set a specific memory limit for the script, '
521 . '"max" for no limit or "default" to avoid changing it',
525 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
526 "http://en.wikipedia.org. This is sometimes necessary because " .
527 "server name detection may fail in command line scripts.", false, true );
528 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
529 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
530 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
532 # Save generic options to display them separately in help
533 $this->mGenericParameters
= $this->mParams
;
535 # Script dependant options:
537 // If we support a DB, show the options
538 if ( $this->getDbType() > 0 ) {
539 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
540 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
543 # Save additional script dependant options to display
544 # Â them separately in help
545 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
552 public function getConfig() {
553 if ( $this->config
=== null ) {
554 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
557 return $this->config
;
562 * @param Config $config
564 public function setConfig( Config
$config ) {
565 $this->config
= $config;
569 * Indicate that the specified extension must be
570 * loaded before the script can run.
572 * This *must* be called in the constructor.
575 * @param string $name
577 protected function requireExtension( $name ) {
578 $this->requiredExtensions
[] = $name;
582 * Verify that the required extensions are installed
586 public function checkRequiredExtensions() {
587 $registry = ExtensionRegistry
::getInstance();
589 foreach ( $this->requiredExtensions
as $name ) {
590 if ( !$registry->isLoaded( $name ) ) {
596 $joined = implode( ', ', $missing );
597 $msg = "The following extensions are required to be installed "
598 . "for this script to run: $joined. Please enable them and then try again.";
599 $this->fatalError( $msg );
604 * Set triggers like when to try to run deferred updates
607 public function setAgentAndTriggers() {
608 if ( function_exists( 'posix_getpwuid' ) ) {
609 $agent = posix_getpwuid( posix_geteuid() )['name'];
613 $agent .= '@' . wfHostname();
615 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
616 // Add a comment for easy SHOW PROCESSLIST interpretation
617 $lbFactory->setAgentName(
618 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
620 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
624 * @param LBFactory $LBFactory
625 * @param Config $config
628 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
629 $services = MediaWikiServices
::getInstance();
630 $stats = $services->getStatsdDataFactory();
631 // Hook into period lag checks which often happen in long-running scripts
632 $lbFactory = $services->getDBLoadBalancerFactory();
633 $lbFactory->setWaitForReplicationListener(
635 function () use ( $stats, $config ) {
636 // Check config in case of JobRunner and unit tests
637 if ( $config->get( 'CommandLineMode' ) ) {
638 DeferredUpdates
::tryOpportunisticExecute( 'run' );
640 // Try to periodically flush buffered metrics to avoid OOMs
641 MediaWiki
::emitBufferedStatsdData( $stats, $config );
644 // Check for other windows to run them. A script may read or do a few writes
645 // to the master but mostly be writing to something else, like a file store.
646 $lbFactory->getMainLB()->setTransactionListener(
648 function ( $trigger ) use ( $stats, $config ) {
649 // Check config in case of JobRunner and unit tests
650 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
651 DeferredUpdates
::tryOpportunisticExecute( 'run' );
653 // Try to periodically flush buffered metrics to avoid OOMs
654 MediaWiki
::emitBufferedStatsdData( $stats, $config );
660 * Run a child maintenance script. Pass all of the current arguments
662 * @param string $maintClass A name of a child maintenance class
663 * @param string $classFile Full path of where the child is
664 * @return Maintenance
666 public function runChild( $maintClass, $classFile = null ) {
667 // Make sure the class is loaded first
668 if ( !class_exists( $maintClass ) ) {
670 require_once $classFile;
672 if ( !class_exists( $maintClass ) ) {
673 $this->error( "Cannot spawn child: $maintClass" );
678 * @var $child Maintenance
680 $child = new $maintClass();
681 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
682 if ( !is_null( $this->mDb
) ) {
683 $child->setDB( $this->mDb
);
690 * Do some sanity checking and basic setup
692 public function setup() {
693 global $IP, $wgCommandLineMode;
695 # Abort if called from a web server
696 # wfIsCLI() is not available yet
697 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
698 $this->fatalError( 'This script must be run from the command line' );
701 if ( $IP === null ) {
702 $this->fatalError( "\$IP not set, aborting!\n" .
703 '(Did you forget to call parent::__construct() in your maintenance script?)' );
706 # Make sure we can handle script parameters
707 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
708 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
711 // Send PHP warnings and errors to stderr instead of stdout.
712 // This aids in diagnosing problems, while keeping messages
713 // out of redirected output.
714 if ( ini_get( 'display_errors' ) ) {
715 ini_set( 'display_errors', 'stderr' );
718 $this->loadParamsAndArgs();
721 # Set the memory limit
722 # Note we need to set it again later in cache LocalSettings changed it
723 $this->adjustMemoryLimit();
725 # Set max execution time to 0 (no limit). PHP.net says that
726 # "When running PHP from the command line the default setting is 0."
727 # But sometimes this doesn't seem to be the case.
728 ini_set( 'max_execution_time', 0 );
730 # Define us as being in MediaWiki
731 define( 'MEDIAWIKI', true );
733 $wgCommandLineMode = true;
735 # Turn off output buffering if it's on
736 while ( ob_get_level() > 0 ) {
740 $this->validateParamsAndArgs();
744 * Normally we disable the memory_limit when running admin scripts.
745 * Some scripts may wish to actually set a limit, however, to avoid
746 * blowing up unexpectedly. We also support a --memory-limit option,
747 * to allow sysadmins to explicitly set one if they'd prefer to override
748 * defaults (or for people using Suhosin which yells at you for trying
749 * to disable the limits)
752 public function memoryLimit() {
753 $limit = $this->getOption( 'memory-limit', 'max' );
754 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
759 * Adjusts PHP's memory limit to better suit our needs, if needed.
761 protected function adjustMemoryLimit() {
762 $limit = $this->memoryLimit();
763 if ( $limit == 'max' ) {
764 $limit = -1; // no memory limit
766 if ( $limit != 'default' ) {
767 ini_set( 'memory_limit', $limit );
772 * Activate the profiler (assuming $wgProfiler is set)
774 protected function activateProfiler() {
775 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
777 $output = $this->getOption( 'profiler' );
782 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
783 $class = $wgProfiler['class'];
784 /** @var Profiler $profiler */
785 $profiler = new $class(
786 [ 'sampling' => 1, 'output' => [ $output ] ]
788 +
[ 'threshold' => $wgProfileLimit ]
790 $profiler->setTemplated( true );
791 Profiler
::replaceStubInstance( $profiler );
794 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
795 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
796 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
800 * Clear all params and arguments.
802 public function clearParamsAndArgs() {
803 $this->mOptions
= [];
805 $this->mInputLoaded
= false;
809 * Load params and arguments from a given array
810 * of command-line arguments
815 public function loadWithArgv( $argv ) {
818 $this->orderedOptions
= [];
821 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
822 if ( $arg == '--' ) {
823 # End of options, remainder should be considered arguments
824 $arg = next( $argv );
825 while ( $arg !== false ) {
827 $arg = next( $argv );
830 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
832 $option = substr( $arg, 2 );
833 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
834 $param = next( $argv );
835 if ( $param === false ) {
836 $this->error( "\nERROR: $option parameter needs a value after it\n" );
837 $this->maybeHelp( true );
840 $this->setParam( $options, $option, $param );
842 $bits = explode( '=', $option, 2 );
843 if ( count( $bits ) > 1 ) {
850 $this->setParam( $options, $option, $param );
852 } elseif ( $arg == '-' ) {
853 # Lonely "-", often used to indicate stdin or stdout.
855 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
857 $argLength = strlen( $arg );
858 for ( $p = 1; $p < $argLength; $p++
) {
860 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
861 $option = $this->mShortParamsMap
[$option];
864 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
865 $param = next( $argv );
866 if ( $param === false ) {
867 $this->error( "\nERROR: $option parameter needs a value after it\n" );
868 $this->maybeHelp( true );
870 $this->setParam( $options, $option, $param );
872 $this->setParam( $options, $option, 1 );
880 $this->mOptions
= $options;
881 $this->mArgs
= $args;
882 $this->loadSpecialVars();
883 $this->mInputLoaded
= true;
887 * Helper function used solely by loadParamsAndArgs
888 * to prevent code duplication
890 * This sets the param in the options array based on
891 * whether or not it can be specified multiple times.
894 * @param array $options
895 * @param string $option
896 * @param mixed $value
898 private function setParam( &$options, $option, $value ) {
899 $this->orderedOptions
[] = [ $option, $value ];
901 if ( isset( $this->mParams
[$option] ) ) {
902 $multi = $this->mParams
[$option]['multiOccurrence'];
906 $exists = array_key_exists( $option, $options );
907 if ( $multi && $exists ) {
908 $options[$option][] = $value;
909 } elseif ( $multi ) {
910 $options[$option] = [ $value ];
911 } elseif ( !$exists ) {
912 $options[$option] = $value;
914 $this->error( "\nERROR: $option parameter given twice\n" );
915 $this->maybeHelp( true );
920 * Process command line arguments
921 * $mOptions becomes an array with keys set to the option names
922 * $mArgs becomes a zero-based array containing the non-option arguments
924 * @param string $self The name of the script, if any
925 * @param array $opts An array of options, in form of key=>value
926 * @param array $args An array of command line arguments
928 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
929 # If we were given opts or args, set those and return early
931 $this->mSelf
= $self;
932 $this->mInputLoaded
= true;
935 $this->mOptions
= $opts;
936 $this->mInputLoaded
= true;
939 $this->mArgs
= $args;
940 $this->mInputLoaded
= true;
943 # If we've already loaded input (either by user values or from $argv)
944 # skip on loading it again. The array_shift() will corrupt values if
945 # it's run again and again
946 if ( $this->mInputLoaded
) {
947 $this->loadSpecialVars();
953 $this->mSelf
= $argv[0];
954 $this->loadWithArgv( array_slice( $argv, 1 ) );
958 * Run some validation checks on the params, etc
960 protected function validateParamsAndArgs() {
962 # Check to make sure we've got all the required options
963 foreach ( $this->mParams
as $opt => $info ) {
964 if ( $info['require'] && !$this->hasOption( $opt ) ) {
965 $this->error( "Param $opt required!" );
970 foreach ( $this->mArgList
as $k => $info ) {
971 if ( $info['require'] && !$this->hasArg( $k ) ) {
972 $this->error( 'Argument <' . $info['name'] . '> required!' );
978 $this->maybeHelp( true );
983 * Handle the special variables that are global to all scripts
985 protected function loadSpecialVars() {
986 if ( $this->hasOption( 'dbuser' ) ) {
987 $this->mDbUser
= $this->getOption( 'dbuser' );
989 if ( $this->hasOption( 'dbpass' ) ) {
990 $this->mDbPass
= $this->getOption( 'dbpass' );
992 if ( $this->hasOption( 'quiet' ) ) {
993 $this->mQuiet
= true;
995 if ( $this->hasOption( 'batch-size' ) ) {
996 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1001 * Maybe show the help.
1002 * @param bool $force Whether to force the help to show, default false
1004 protected function maybeHelp( $force = false ) {
1005 if ( !$force && !$this->hasOption( 'help' ) ) {
1009 $screenWidth = 80; // TODO: Calculate this!
1011 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1013 ksort( $this->mParams
);
1014 $this->mQuiet
= false;
1017 if ( $this->mDescription
) {
1018 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1020 $output = "\nUsage: php " . basename( $this->mSelf
);
1022 // ... append parameters ...
1023 if ( $this->mParams
) {
1024 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1027 // ... and append arguments.
1028 if ( $this->mArgList
) {
1030 foreach ( $this->mArgList
as $k => $arg ) {
1031 if ( $arg['require'] ) {
1032 $output .= '<' . $arg['name'] . '>';
1034 $output .= '[' . $arg['name'] . ']';
1036 if ( $k < count( $this->mArgList
) - 1 ) {
1041 $this->output( "$output\n\n" );
1043 # TODO abstract some repetitive code below
1045 // Generic parameters
1046 $this->output( "Generic maintenance parameters:\n" );
1047 foreach ( $this->mGenericParameters
as $par => $info ) {
1048 if ( $info['shortName'] !== false ) {
1049 $par .= " (-{$info['shortName']})";
1052 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1053 "\n$tab$tab" ) . "\n"
1056 $this->output( "\n" );
1058 $scriptDependantParams = $this->mDependantParameters
;
1059 if ( count( $scriptDependantParams ) > 0 ) {
1060 $this->output( "Script dependant parameters:\n" );
1061 // Parameters description
1062 foreach ( $scriptDependantParams as $par => $info ) {
1063 if ( $info['shortName'] !== false ) {
1064 $par .= " (-{$info['shortName']})";
1067 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1068 "\n$tab$tab" ) . "\n"
1071 $this->output( "\n" );
1074 // Script specific parameters not defined on construction by
1075 // Maintenance::addDefaultParams()
1076 $scriptSpecificParams = array_diff_key(
1077 # all script parameters:
1079 # remove the Maintenance default parameters:
1080 $this->mGenericParameters
,
1081 $this->mDependantParameters
1083 if ( count( $scriptSpecificParams ) > 0 ) {
1084 $this->output( "Script specific parameters:\n" );
1085 // Parameters description
1086 foreach ( $scriptSpecificParams as $par => $info ) {
1087 if ( $info['shortName'] !== false ) {
1088 $par .= " (-{$info['shortName']})";
1091 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1092 "\n$tab$tab" ) . "\n"
1095 $this->output( "\n" );
1099 if ( count( $this->mArgList
) > 0 ) {
1100 $this->output( "Arguments:\n" );
1101 // Arguments description
1102 foreach ( $this->mArgList
as $info ) {
1103 $openChar = $info['require'] ?
'<' : '[';
1104 $closeChar = $info['require'] ?
'>' : ']';
1106 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1107 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1110 $this->output( "\n" );
1117 * Handle some last-minute setup here.
1119 public function finalSetup() {
1120 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1121 global $wgDBadminuser, $wgDBadminpassword;
1122 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1124 # Turn off output buffering again, it might have been turned on in the settings files
1125 if ( ob_get_level() ) {
1129 $wgCommandLineMode = true;
1131 # Override $wgServer
1132 if ( $this->hasOption( 'server' ) ) {
1133 $wgServer = $this->getOption( 'server', $wgServer );
1136 # If these were passed, use them
1137 if ( $this->mDbUser
) {
1138 $wgDBadminuser = $this->mDbUser
;
1140 if ( $this->mDbPass
) {
1141 $wgDBadminpassword = $this->mDbPass
;
1144 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1145 $wgDBuser = $wgDBadminuser;
1146 $wgDBpassword = $wgDBadminpassword;
1148 if ( $wgDBservers ) {
1150 * @var $wgDBservers array
1152 foreach ( $wgDBservers as $i => $server ) {
1153 $wgDBservers[$i]['user'] = $wgDBuser;
1154 $wgDBservers[$i]['password'] = $wgDBpassword;
1157 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1158 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1159 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1161 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1164 # Apply debug settings
1165 if ( $this->hasOption( 'mwdebug' ) ) {
1166 require __DIR__
. '/../includes/DevelopmentSettings.php';
1169 // Per-script profiling; useful for debugging
1170 $this->activateProfiler();
1172 $this->afterFinalSetup();
1174 $wgShowSQLErrors = true;
1176 Wikimedia\
suppressWarnings();
1177 set_time_limit( 0 );
1178 Wikimedia\restoreWarnings
();
1180 $this->adjustMemoryLimit();
1184 * Execute a callback function at the end of initialisation
1186 protected function afterFinalSetup() {
1187 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1188 call_user_func( MW_CMDLINE_CALLBACK
);
1193 * Potentially debug globals. Originally a feature only
1196 public function globals() {
1197 if ( $this->hasOption( 'globals' ) ) {
1198 print_r( $GLOBALS );
1203 * Generic setup for most installs. Returns the location of LocalSettings
1206 public function loadSettings() {
1207 global $wgCommandLineMode, $IP;
1209 if ( isset( $this->mOptions
['conf'] ) ) {
1210 $settingsFile = $this->mOptions
['conf'];
1211 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1212 $settingsFile = MW_CONFIG_FILE
;
1214 $settingsFile = "$IP/LocalSettings.php";
1216 if ( isset( $this->mOptions
['wiki'] ) ) {
1217 $bits = explode( '-', $this->mOptions
['wiki'] );
1218 if ( count( $bits ) == 1 ) {
1221 define( 'MW_DB', $bits[0] );
1222 define( 'MW_PREFIX', $bits[1] );
1223 } elseif ( isset( $this->mOptions
['server'] ) ) {
1224 // Provide the option for site admins to detect and configure
1225 // multiple wikis based on server names. This offers --server
1226 // as alternative to --wiki.
1227 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1228 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1231 if ( !is_readable( $settingsFile ) ) {
1232 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1233 "must exist and be readable in the source directory.\n" .
1234 "Use --conf to specify it." );
1236 $wgCommandLineMode = true;
1238 return $settingsFile;
1242 * Support function for cleaning up redundant text records
1243 * @param bool $delete Whether or not to actually delete the records
1244 * @author Rob Church <robchur@gmail.com>
1246 public function purgeRedundantText( $delete = true ) {
1247 # Data should come off the master, wrapped in a transaction
1248 $dbw = $this->getDB( DB_MASTER
);
1249 $this->beginTransaction( $dbw, __METHOD__
);
1251 # Get "active" text records from the revisions table
1253 $this->output( 'Searching for active text records in revisions table...' );
1254 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1255 foreach ( $res as $row ) {
1256 $cur[] = $row->rev_text_id
;
1258 $this->output( "done.\n" );
1260 # Get "active" text records from the archive table
1261 $this->output( 'Searching for active text records in archive table...' );
1262 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1263 foreach ( $res as $row ) {
1264 # old pre-MW 1.5 records can have null ar_text_id's.
1265 if ( $row->ar_text_id
!== null ) {
1266 $cur[] = $row->ar_text_id
;
1269 $this->output( "done.\n" );
1271 # Get the IDs of all text records not in these sets
1272 $this->output( 'Searching for inactive text records...' );
1273 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1274 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1276 foreach ( $res as $row ) {
1277 $old[] = $row->old_id
;
1279 $this->output( "done.\n" );
1281 # Inform the user of what we're going to do
1282 $count = count( $old );
1283 $this->output( "$count inactive items found.\n" );
1285 # Delete as appropriate
1286 if ( $delete && $count ) {
1287 $this->output( 'Deleting...' );
1288 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1289 $this->output( "done.\n" );
1293 $this->commitTransaction( $dbw, __METHOD__
);
1297 * Get the maintenance directory.
1300 protected function getDir() {
1305 * Returns a database to be used by current maintenance script. It can be set by setDB().
1306 * If not set, wfGetDB() will be used.
1307 * This function has the same parameters as wfGetDB()
1309 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1310 * @param string|string[] $groups default: empty array
1311 * @param string|bool $wiki default: current wiki
1312 * @return IMaintainableDatabase
1314 protected function getDB( $db, $groups = [], $wiki = false ) {
1315 if ( is_null( $this->mDb
) ) {
1316 return wfGetDB( $db, $groups, $wiki );
1323 * Sets database object to be returned by getDB().
1325 * @param IDatabase $db
1327 public function setDB( IDatabase
$db ) {
1332 * Begin a transcation on a DB
1334 * This method makes it clear that begin() is called from a maintenance script,
1335 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1337 * @param IDatabase $dbw
1338 * @param string $fname Caller name
1341 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1342 $dbw->begin( $fname );
1346 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1348 * This method makes it clear that commit() is called from a maintenance script,
1349 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1351 * @param IDatabase $dbw
1352 * @param string $fname Caller name
1353 * @return bool Whether the replica DB wait succeeded
1356 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1357 $dbw->commit( $fname );
1359 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1360 $lbFactory->waitForReplication(
1361 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1363 $this->lastReplicationWait
= microtime( true );
1366 } catch ( DBReplicationWaitError
$e ) {
1372 * Rollback the transcation on a DB handle
1374 * This method makes it clear that rollback() is called from a maintenance script,
1375 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1377 * @param IDatabase $dbw
1378 * @param string $fname Caller name
1381 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1382 $dbw->rollback( $fname );
1386 * Lock the search index
1387 * @param IMaintainableDatabase &$db
1389 private function lockSearchindex( $db ) {
1390 $write = [ 'searchindex' ];
1400 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1405 * @param IMaintainableDatabase &$db
1407 private function unlockSearchindex( $db ) {
1408 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1412 * Unlock and lock again
1413 * Since the lock is low-priority, queued reads will be able to complete
1414 * @param IMaintainableDatabase &$db
1416 private function relockSearchindex( $db ) {
1417 $this->unlockSearchindex( $db );
1418 $this->lockSearchindex( $db );
1422 * Perform a search index update with locking
1423 * @param int $maxLockTime The maximum time to keep the search index locked.
1424 * @param string $callback The function that will update the function.
1425 * @param IMaintainableDatabase $dbw
1426 * @param array $results
1428 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1432 if ( $maxLockTime ) {
1433 $this->output( " --- Waiting for lock ---" );
1434 $this->lockSearchindex( $dbw );
1436 $this->output( "\n" );
1439 # Loop through the results and do a search update
1440 foreach ( $results as $row ) {
1441 # Allow reads to be processed
1442 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1443 $this->output( " --- Relocking ---" );
1444 $this->relockSearchindex( $dbw );
1446 $this->output( "\n" );
1448 call_user_func( $callback, $dbw, $row );
1451 # Unlock searchindex
1452 if ( $maxLockTime ) {
1453 $this->output( " --- Unlocking --" );
1454 $this->unlockSearchindex( $dbw );
1455 $this->output( "\n" );
1460 * Update the searchindex table for a given pageid
1461 * @param IDatabase $dbw A database write handle
1462 * @param int $pageId The page ID to update.
1463 * @return null|string
1465 public function updateSearchIndexForPage( $dbw, $pageId ) {
1466 // Get current revision
1467 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1470 $titleObj = $rev->getTitle();
1471 $title = $titleObj->getPrefixedDBkey();
1472 $this->output( "$title..." );
1473 # Update searchindex
1474 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1476 $this->output( "\n" );
1483 * Count down from $seconds to zero on the terminal, with a one-second pause
1484 * between showing each number. If the maintenance script is in quiet mode,
1485 * this function does nothing.
1489 * @codeCoverageIgnore
1490 * @param int $seconds
1492 protected function countDown( $seconds ) {
1493 if ( $this->isQuiet() ) {
1496 for ( $i = $seconds; $i >= 0; $i-- ) {
1497 if ( $i != $seconds ) {
1498 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1500 $this->output( $i );
1505 $this->output( "\n" );
1509 * Wrapper for posix_isatty()
1510 * We default as considering stdin a tty (for nice readline methods)
1511 * but treating stout as not a tty to avoid color codes
1513 * @param mixed $fd File descriptor
1516 public static function posix_isatty( $fd ) {
1517 if ( !function_exists( 'posix_isatty' ) ) {
1520 return posix_isatty( $fd );
1525 * Prompt the console for input
1526 * @param string $prompt What to begin the line with, like '> '
1527 * @return string Response
1529 public static function readconsole( $prompt = '> ' ) {
1530 static $isatty = null;
1531 if ( is_null( $isatty ) ) {
1532 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1535 if ( $isatty && function_exists( 'readline' ) ) {
1536 return readline( $prompt );
1539 $st = self
::readlineEmulation( $prompt );
1541 if ( feof( STDIN
) ) {
1544 $st = fgets( STDIN
, 1024 );
1547 if ( $st === false ) {
1550 $resp = trim( $st );
1557 * Emulate readline()
1558 * @param string $prompt What to begin the line with, like '> '
1561 private static function readlineEmulation( $prompt ) {
1562 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1563 if ( !wfIsWindows() && $bash ) {
1565 $encPrompt = wfEscapeShellArg( $prompt );
1566 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1567 $encCommand = wfEscapeShellArg( $command );
1568 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1570 if ( $retval == 0 ) {
1572 } elseif ( $retval == 127 ) {
1573 // Couldn't execute bash even though we thought we saw it.
1574 // Shell probably spit out an error message, sorry :(
1575 // Fall through to fgets()...
1582 // Fallback... we'll have no editing controls, EWWW
1583 if ( feof( STDIN
) ) {
1588 return fgets( STDIN
, 1024 );
1592 * Get the terminal size as a two-element array where the first element
1593 * is the width (number of columns) and the second element is the height
1598 public static function getTermSize() {
1599 $default = [ 80, 50 ];
1600 if ( wfIsWindows() ) {
1603 // It's possible to get the screen size with VT-100 terminal escapes,
1604 // but reading the responses is not possible without setting raw mode
1605 // (unless you want to require the user to press enter), and that
1606 // requires an ioctl(), which we can't do. So we have to shell out to
1607 // something that can do the relevant syscalls. There are a few
1608 // options. Linux and Mac OS X both have "stty size" which does the
1610 $result = Shell
::command( 'stty', 'size' )
1612 if ( $result->getExitCode() !== 0 ) {
1615 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1618 return [ intval( $m[2] ), intval( $m[1] ) ];
1622 * Call this to set up the autoloader to allow classes to be used from the
1625 public static function requireTestsAutoloader() {
1626 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1631 * Fake maintenance wrapper, mostly used for the web installer/updater
1633 class FakeMaintenance
extends Maintenance
{
1634 protected $mSelf = "FakeMaintenanceScript";
1636 public function execute() {
1642 * Class for scripts that perform database maintenance and want to log the
1643 * update in `updatelog` so we can later skip it
1645 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1646 public function __construct() {
1647 parent
::__construct();
1648 $this->addOption( 'force', 'Run the update even if it was completed already' );
1649 $this->setBatchSize( 200 );
1652 public function execute() {
1653 $db = $this->getDB( DB_MASTER
);
1654 $key = $this->getUpdateKey();
1656 if ( !$this->hasOption( 'force' )
1657 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1659 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1664 if ( !$this->doDBUpdates() ) {
1668 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1671 $this->output( $this->updatelogFailedMessage() . "\n" );
1678 * Message to show that the update was done already and was just skipped
1681 protected function updateSkippedMessage() {
1682 $key = $this->getUpdateKey();
1684 return "Update '{$key}' already logged as completed.";
1688 * Message to show that the update log was unable to log the completion of this update
1691 protected function updatelogFailedMessage() {
1692 $key = $this->getUpdateKey();
1694 return "Unable to log update '{$key}' as completed.";
1698 * Do the actual work. All child classes will need to implement this.
1699 * Return true to log the update as done or false (usually on failure).
1702 abstract protected function doDBUpdates();
1705 * Get the update key name to go in the update log table
1708 abstract protected function getUpdateKey();