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 // Allow arbitrary options to be passed, or only specified ones?
89 protected $mAllowUnregisteredOptions = false;
91 // Name of the script currently running
94 // Special vars for params that are always used
95 protected $mQuiet = false;
96 protected $mDbUser, $mDbPass;
98 // A description of the script, children should change this via addDescription()
99 protected $mDescription = '';
101 // Have we already loaded our user input?
102 protected $mInputLoaded = false;
105 * Batch size. If a script supports this, they should set
106 * a default with setBatchSize()
110 protected $mBatchSize = null;
112 // Generic options added by addDefaultParams()
113 private $mGenericParameters = [];
114 // Generic options which might or not be supported by the script
115 private $mDependantParameters = [];
118 * Used by getDB() / setDB()
119 * @var IMaintainableDatabase
123 /** @var float UNIX timestamp */
124 private $lastReplicationWait = 0.0;
127 * Used when creating separate schema files.
133 * Accessible via getConfig()
140 * @see Maintenance::requireExtension
143 private $requiredExtensions = [];
146 * Used to read the options in the order they were passed.
147 * Useful for option chaining (Ex. dumpBackup.php). It will
148 * be an empty array if the options are passed in through
149 * loadParamsAndArgs( $self, $opts, $args ).
151 * This is an array of arrays where
152 * 0 => the option and 1 => parameter value.
156 public $orderedOptions = [];
159 * Default constructor. Children should call this *first* if implementing
160 * their own constructors
162 public function __construct() {
163 // Setup $IP, using MW_INSTALL_PATH if it exists
165 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
166 ?
getenv( 'MW_INSTALL_PATH' )
167 : realpath( __DIR__
. '/..' );
169 $this->addDefaultParams();
170 register_shutdown_function( [ $this, 'outputChanneled' ], false );
174 * Should we execute the maintenance script, or just allow it to be included
175 * as a standalone class? It checks that the call stack only includes this
176 * function and "requires" (meaning was called from the file scope)
180 public static function shouldExecute() {
181 global $wgCommandLineMode;
183 if ( !function_exists( 'debug_backtrace' ) ) {
184 // If someone has a better idea...
185 return $wgCommandLineMode;
188 $bt = debug_backtrace();
189 $count = count( $bt );
191 return false; // sanity
193 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
194 return false; // last call should be to this function
196 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
197 for ( $i = 1; $i < $count; $i++
) {
198 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
199 return false; // previous calls should all be "requires"
207 * Do the actual work. All child classes will need to implement this
209 * @return bool|null|void True for success, false for failure. Not returning
210 * a value, or returning null, is also interpreted as success. Returning
211 * false for failure will cause doMaintenance.php to exit the process
212 * with a non-zero exit status.
214 abstract public function execute();
217 * Checks to see if a particular option in supported. Normally this means it
218 * has been registered by the script via addOption.
219 * @param string $name The name of the option
220 * @return bool true if the option exists, false otherwise
222 protected function supportsOption( $name ) {
223 return isset( $this->mParams
[$name] );
227 * Add a parameter to the script. Will be displayed on --help
228 * with the associated description
230 * @param string $name The name of the param (help, version, etc)
231 * @param string $description The description of the param to show on --help
232 * @param bool $required Is the param required?
233 * @param bool $withArg Is an argument required with this option?
234 * @param string|bool $shortName Character to use as short name
235 * @param bool $multiOccurrence Can this option be passed multiple times?
237 protected function addOption( $name, $description, $required = false,
238 $withArg = false, $shortName = false, $multiOccurrence = false
240 $this->mParams
[$name] = [
241 'desc' => $description,
242 'require' => $required,
243 'withArg' => $withArg,
244 'shortName' => $shortName,
245 'multiOccurrence' => $multiOccurrence
248 if ( $shortName !== false ) {
249 $this->mShortParamsMap
[$shortName] = $name;
254 * Checks to see if a particular option exists.
255 * @param string $name The name of the option
258 protected function hasOption( $name ) {
259 return isset( $this->mOptions
[$name] );
263 * Get an option, or return the default.
265 * If the option was added to support multiple occurrences,
266 * this will return an array.
268 * @param string $name The name of the param
269 * @param mixed|null $default Anything you want, default null
272 protected function getOption( $name, $default = null ) {
273 if ( $this->hasOption( $name ) ) {
274 return $this->mOptions
[$name];
276 // Set it so we don't have to provide the default again
277 $this->mOptions
[$name] = $default;
279 return $this->mOptions
[$name];
284 * Add some args that are needed
285 * @param string $arg Name of the arg, like 'start'
286 * @param string $description Short description of the arg
287 * @param bool $required Is this required?
289 protected function addArg( $arg, $description, $required = true ) {
290 $this->mArgList
[] = [
292 'desc' => $description,
293 'require' => $required
298 * Remove an option. Useful for removing options that won't be used in your script.
299 * @param string $name The option to remove.
301 protected function deleteOption( $name ) {
302 unset( $this->mParams
[$name] );
306 * Sets whether to allow unregistered options, which are options passed to
307 * a script that do not match an expected parameter.
308 * @param bool $allow Should we allow?
310 protected function setAllowUnregisteredOptions( $allow ) {
311 $this->mAllowUnregisteredOptions
= $allow;
315 * Set the description text.
316 * @param string $text The text of the description
318 protected function addDescription( $text ) {
319 $this->mDescription
= $text;
323 * Does a given argument exist?
324 * @param int $argId The integer value (from zero) for the arg
327 protected function hasArg( $argId = 0 ) {
328 return isset( $this->mArgs
[$argId] );
333 * @param int $argId The integer value (from zero) for the arg
334 * @param mixed|null $default The default if it doesn't exist
337 protected function getArg( $argId = 0, $default = null ) {
338 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
348 protected function getBatchSize() {
349 return $this->mBatchSize
;
353 * Set the batch size.
354 * @param int $s The number of operations to do in a batch
356 protected function setBatchSize( $s = 0 ) {
357 $this->mBatchSize
= $s;
359 // If we support $mBatchSize, show the option.
360 // Used to be in addDefaultParams, but in order for that to
361 // work, subclasses would have to call this function in the constructor
362 // before they called parent::__construct which is just weird
363 // (and really wasn't done).
364 if ( $this->mBatchSize
) {
365 $this->addOption( 'batch-size', 'Run this many operations ' .
366 'per batch, default: ' . $this->mBatchSize
, false, true );
367 if ( isset( $this->mParams
['batch-size'] ) ) {
368 // This seems a little ugly...
369 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
375 * Get the script's name
378 public function getName() {
383 * Return input from stdin.
384 * @param int|null $len The number of bytes to read. If null, just return the handle.
385 * Maintenance::STDIN_ALL returns the full length
388 protected function getStdin( $len = null ) {
389 if ( $len == self
::STDIN_ALL
) {
390 return file_get_contents( 'php://stdin' );
392 $f = fopen( 'php://stdin', 'rt' );
396 $input = fgets( $f, $len );
399 return rtrim( $input );
405 public function isQuiet() {
406 return $this->mQuiet
;
410 * Throw some output to the user. Scripts can call this with no fears,
411 * as we handle all --quiet stuff here
412 * @param string $out The text to show to the user
413 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
415 protected function output( $out, $channel = null ) {
416 // This is sometimes called very early, before Setup.php is included.
417 if ( class_exists( MediaWikiServices
::class ) ) {
418 // Try to periodically flush buffered metrics to avoid OOMs
419 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
420 if ( $stats->getDataCount() > 1000 ) {
421 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
425 if ( $this->mQuiet
) {
428 if ( $channel === null ) {
429 $this->cleanupChanneled();
432 $out = preg_replace( '/\n\z/', '', $out );
433 $this->outputChanneled( $out, $channel );
438 * Throw an error to the user. Doesn't respect --quiet, so don't use
439 * this for non-error output
440 * @param string $err The error to display
441 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
443 protected function error( $err, $die = 0 ) {
444 if ( intval( $die ) !== 0 ) {
445 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
446 $this->fatalError( $err, intval( $die ) );
448 $this->outputChanneled( false );
450 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
451 !defined( 'MW_PHPUNIT_TEST' )
453 fwrite( STDERR
, $err . "\n" );
460 * Output a message and terminate the current script.
462 * @param string $msg Error message
463 * @param int $exitCode PHP exit status. Should be in range 1-254.
466 protected function fatalError( $msg, $exitCode = 1 ) {
467 $this->error( $msg );
471 private $atLineStart = true;
472 private $lastChannel = null;
475 * Clean up channeled output. Output a newline if necessary.
477 public function cleanupChanneled() {
478 if ( !$this->atLineStart
) {
480 $this->atLineStart
= true;
485 * Message outputter with channeled message support. Messages on the
486 * same channel are concatenated, but any intervening messages in another
487 * channel start a new line.
488 * @param string $msg The message without trailing newline
489 * @param string|null $channel Channel identifier or null for no
490 * channel. Channel comparison uses ===.
492 public function outputChanneled( $msg, $channel = null ) {
493 if ( $msg === false ) {
494 $this->cleanupChanneled();
499 // End the current line if necessary
500 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
506 $this->atLineStart
= false;
507 if ( $channel === null ) {
508 // For unchanneled messages, output trailing newline immediately
510 $this->atLineStart
= true;
512 $this->lastChannel
= $channel;
516 * Does the script need different DB access? By default, we give Maintenance
517 * scripts normal rights to the DB. Sometimes, a script needs admin rights
518 * access for a reason and sometimes they want no access. Subclasses should
519 * override and return one of the following values, as needed:
520 * Maintenance::DB_NONE - For no DB access at all
521 * Maintenance::DB_STD - For normal DB access, default
522 * Maintenance::DB_ADMIN - For admin DB access
525 public function getDbType() {
530 * Add the default parameters to the scripts
532 protected function addDefaultParams() {
533 # Generic (non script dependant) options:
535 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
536 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
537 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
538 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
539 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
542 'Set a specific memory limit for the script, '
543 . '"max" for no limit or "default" to avoid changing it',
547 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
548 "http://en.wikipedia.org. This is sometimes necessary because " .
549 "server name detection may fail in command line scripts.", false, true );
550 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
551 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
552 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
554 # Save generic options to display them separately in help
555 $this->mGenericParameters
= $this->mParams
;
557 # Script dependant options:
559 // If we support a DB, show the options
560 if ( $this->getDbType() > 0 ) {
561 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
562 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
563 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
566 # Save additional script dependant options to display
567 # Â them separately in help
568 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
575 public function getConfig() {
576 if ( $this->config
=== null ) {
577 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
580 return $this->config
;
585 * @param Config $config
587 public function setConfig( Config
$config ) {
588 $this->config
= $config;
592 * Indicate that the specified extension must be
593 * loaded before the script can run.
595 * This *must* be called in the constructor.
598 * @param string $name
600 protected function requireExtension( $name ) {
601 $this->requiredExtensions
[] = $name;
605 * Verify that the required extensions are installed
609 public function checkRequiredExtensions() {
610 $registry = ExtensionRegistry
::getInstance();
612 foreach ( $this->requiredExtensions
as $name ) {
613 if ( !$registry->isLoaded( $name ) ) {
619 $joined = implode( ', ', $missing );
620 $msg = "The following extensions are required to be installed "
621 . "for this script to run: $joined. Please enable them and then try again.";
622 $this->fatalError( $msg );
627 * Set triggers like when to try to run deferred updates
630 public function setAgentAndTriggers() {
631 if ( function_exists( 'posix_getpwuid' ) ) {
632 $agent = posix_getpwuid( posix_geteuid() )['name'];
636 $agent .= '@' . wfHostname();
638 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
639 // Add a comment for easy SHOW PROCESSLIST interpretation
640 $lbFactory->setAgentName(
641 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
643 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
647 * @param LBFactory $LBFactory
648 * @param Config $config
651 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
652 $services = MediaWikiServices
::getInstance();
653 $stats = $services->getStatsdDataFactory();
654 // Hook into period lag checks which often happen in long-running scripts
655 $lbFactory = $services->getDBLoadBalancerFactory();
656 $lbFactory->setWaitForReplicationListener(
658 function () use ( $stats, $config ) {
659 // Check config in case of JobRunner and unit tests
660 if ( $config->get( 'CommandLineMode' ) ) {
661 DeferredUpdates
::tryOpportunisticExecute( 'run' );
663 // Try to periodically flush buffered metrics to avoid OOMs
664 MediaWiki
::emitBufferedStatsdData( $stats, $config );
667 // Check for other windows to run them. A script may read or do a few writes
668 // to the master but mostly be writing to something else, like a file store.
669 $lbFactory->getMainLB()->setTransactionListener(
671 function ( $trigger ) use ( $stats, $config ) {
672 // Check config in case of JobRunner and unit tests
673 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
674 DeferredUpdates
::tryOpportunisticExecute( 'run' );
676 // Try to periodically flush buffered metrics to avoid OOMs
677 MediaWiki
::emitBufferedStatsdData( $stats, $config );
683 * Run a child maintenance script. Pass all of the current arguments
685 * @param string $maintClass A name of a child maintenance class
686 * @param string|null $classFile Full path of where the child is
687 * @return Maintenance
689 public function runChild( $maintClass, $classFile = null ) {
690 // Make sure the class is loaded first
691 if ( !class_exists( $maintClass ) ) {
693 require_once $classFile;
695 if ( !class_exists( $maintClass ) ) {
696 $this->error( "Cannot spawn child: $maintClass" );
701 * @var $child Maintenance
703 $child = new $maintClass();
704 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
705 if ( !is_null( $this->mDb
) ) {
706 $child->setDB( $this->mDb
);
713 * Do some sanity checking and basic setup
715 public function setup() {
716 global $IP, $wgCommandLineMode;
718 # Abort if called from a web server
719 # wfIsCLI() is not available yet
720 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
721 $this->fatalError( 'This script must be run from the command line' );
724 if ( $IP === null ) {
725 $this->fatalError( "\$IP not set, aborting!\n" .
726 '(Did you forget to call parent::__construct() in your maintenance script?)' );
729 # Make sure we can handle script parameters
730 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
731 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
734 // Send PHP warnings and errors to stderr instead of stdout.
735 // This aids in diagnosing problems, while keeping messages
736 // out of redirected output.
737 if ( ini_get( 'display_errors' ) ) {
738 ini_set( 'display_errors', 'stderr' );
741 $this->loadParamsAndArgs();
744 # Set the memory limit
745 # Note we need to set it again later in cache LocalSettings changed it
746 $this->adjustMemoryLimit();
748 # Set max execution time to 0 (no limit). PHP.net says that
749 # "When running PHP from the command line the default setting is 0."
750 # But sometimes this doesn't seem to be the case.
751 ini_set( 'max_execution_time', 0 );
753 # Define us as being in MediaWiki
754 define( 'MEDIAWIKI', true );
756 $wgCommandLineMode = true;
758 # Turn off output buffering if it's on
759 while ( ob_get_level() > 0 ) {
763 $this->validateParamsAndArgs();
767 * Normally we disable the memory_limit when running admin scripts.
768 * Some scripts may wish to actually set a limit, however, to avoid
769 * blowing up unexpectedly. We also support a --memory-limit option,
770 * to allow sysadmins to explicitly set one if they'd prefer to override
771 * defaults (or for people using Suhosin which yells at you for trying
772 * to disable the limits)
775 public function memoryLimit() {
776 $limit = $this->getOption( 'memory-limit', 'max' );
777 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
782 * Adjusts PHP's memory limit to better suit our needs, if needed.
784 protected function adjustMemoryLimit() {
785 $limit = $this->memoryLimit();
786 if ( $limit == 'max' ) {
787 $limit = -1; // no memory limit
789 if ( $limit != 'default' ) {
790 ini_set( 'memory_limit', $limit );
795 * Activate the profiler (assuming $wgProfiler is set)
797 protected function activateProfiler() {
798 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
800 $output = $this->getOption( 'profiler' );
805 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
806 $class = $wgProfiler['class'];
807 /** @var Profiler $profiler */
808 $profiler = new $class(
809 [ 'sampling' => 1, 'output' => [ $output ] ]
811 +
[ 'threshold' => $wgProfileLimit ]
813 $profiler->setTemplated( true );
814 Profiler
::replaceStubInstance( $profiler );
817 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
818 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
819 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
823 * Clear all params and arguments.
825 public function clearParamsAndArgs() {
826 $this->mOptions
= [];
828 $this->mInputLoaded
= false;
832 * Load params and arguments from a given array
833 * of command-line arguments
838 public function loadWithArgv( $argv ) {
841 $this->orderedOptions
= [];
844 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
845 if ( $arg == '--' ) {
846 # End of options, remainder should be considered arguments
847 $arg = next( $argv );
848 while ( $arg !== false ) {
850 $arg = next( $argv );
853 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
855 $option = substr( $arg, 2 );
856 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
857 $param = next( $argv );
858 if ( $param === false ) {
859 $this->error( "\nERROR: $option parameter needs a value after it\n" );
860 $this->maybeHelp( true );
863 $this->setParam( $options, $option, $param );
865 $bits = explode( '=', $option, 2 );
866 if ( count( $bits ) > 1 ) {
873 $this->setParam( $options, $option, $param );
875 } elseif ( $arg == '-' ) {
876 # Lonely "-", often used to indicate stdin or stdout.
878 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
880 $argLength = strlen( $arg );
881 for ( $p = 1; $p < $argLength; $p++
) {
883 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
884 $option = $this->mShortParamsMap
[$option];
887 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
888 $param = next( $argv );
889 if ( $param === false ) {
890 $this->error( "\nERROR: $option parameter needs a value after it\n" );
891 $this->maybeHelp( true );
893 $this->setParam( $options, $option, $param );
895 $this->setParam( $options, $option, 1 );
903 $this->mOptions
= $options;
904 $this->mArgs
= $args;
905 $this->loadSpecialVars();
906 $this->mInputLoaded
= true;
910 * Helper function used solely by loadParamsAndArgs
911 * to prevent code duplication
913 * This sets the param in the options array based on
914 * whether or not it can be specified multiple times.
917 * @param array $options
918 * @param string $option
919 * @param mixed $value
921 private function setParam( &$options, $option, $value ) {
922 $this->orderedOptions
[] = [ $option, $value ];
924 if ( isset( $this->mParams
[$option] ) ) {
925 $multi = $this->mParams
[$option]['multiOccurrence'];
929 $exists = array_key_exists( $option, $options );
930 if ( $multi && $exists ) {
931 $options[$option][] = $value;
932 } elseif ( $multi ) {
933 $options[$option] = [ $value ];
934 } elseif ( !$exists ) {
935 $options[$option] = $value;
937 $this->error( "\nERROR: $option parameter given twice\n" );
938 $this->maybeHelp( true );
943 * Process command line arguments
944 * $mOptions becomes an array with keys set to the option names
945 * $mArgs becomes a zero-based array containing the non-option arguments
947 * @param string|null $self The name of the script, if any
948 * @param array|null $opts An array of options, in form of key=>value
949 * @param array|null $args An array of command line arguments
951 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
952 # If we were given opts or args, set those and return early
954 $this->mSelf
= $self;
955 $this->mInputLoaded
= true;
958 $this->mOptions
= $opts;
959 $this->mInputLoaded
= true;
962 $this->mArgs
= $args;
963 $this->mInputLoaded
= true;
966 # If we've already loaded input (either by user values or from $argv)
967 # skip on loading it again. The array_shift() will corrupt values if
968 # it's run again and again
969 if ( $this->mInputLoaded
) {
970 $this->loadSpecialVars();
976 $this->mSelf
= $argv[0];
977 $this->loadWithArgv( array_slice( $argv, 1 ) );
981 * Run some validation checks on the params, etc
983 protected function validateParamsAndArgs() {
985 # Check to make sure we've got all the required options
986 foreach ( $this->mParams
as $opt => $info ) {
987 if ( $info['require'] && !$this->hasOption( $opt ) ) {
988 $this->error( "Param $opt required!" );
993 foreach ( $this->mArgList
as $k => $info ) {
994 if ( $info['require'] && !$this->hasArg( $k ) ) {
995 $this->error( 'Argument <' . $info['name'] . '> required!' );
999 if ( !$this->mAllowUnregisteredOptions
) {
1000 # Check for unexpected options
1001 foreach ( $this->mOptions
as $opt => $val ) {
1002 if ( !$this->supportsOption( $opt ) ) {
1003 $this->error( "Unexpected option $opt!" );
1010 $this->maybeHelp( true );
1015 * Handle the special variables that are global to all scripts
1017 protected function loadSpecialVars() {
1018 if ( $this->hasOption( 'dbuser' ) ) {
1019 $this->mDbUser
= $this->getOption( 'dbuser' );
1021 if ( $this->hasOption( 'dbpass' ) ) {
1022 $this->mDbPass
= $this->getOption( 'dbpass' );
1024 if ( $this->hasOption( 'quiet' ) ) {
1025 $this->mQuiet
= true;
1027 if ( $this->hasOption( 'batch-size' ) ) {
1028 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1033 * Maybe show the help.
1034 * @param bool $force Whether to force the help to show, default false
1036 protected function maybeHelp( $force = false ) {
1037 if ( !$force && !$this->hasOption( 'help' ) ) {
1041 $screenWidth = 80; // TODO: Calculate this!
1043 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1045 ksort( $this->mParams
);
1046 $this->mQuiet
= false;
1049 if ( $this->mDescription
) {
1050 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1052 $output = "\nUsage: php " . basename( $this->mSelf
);
1054 // ... append parameters ...
1055 if ( $this->mParams
) {
1056 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1059 // ... and append arguments.
1060 if ( $this->mArgList
) {
1062 foreach ( $this->mArgList
as $k => $arg ) {
1063 if ( $arg['require'] ) {
1064 $output .= '<' . $arg['name'] . '>';
1066 $output .= '[' . $arg['name'] . ']';
1068 if ( $k < count( $this->mArgList
) - 1 ) {
1073 $this->output( "$output\n\n" );
1075 # TODO abstract some repetitive code below
1077 // Generic parameters
1078 $this->output( "Generic maintenance parameters:\n" );
1079 foreach ( $this->mGenericParameters
as $par => $info ) {
1080 if ( $info['shortName'] !== false ) {
1081 $par .= " (-{$info['shortName']})";
1084 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1085 "\n$tab$tab" ) . "\n"
1088 $this->output( "\n" );
1090 $scriptDependantParams = $this->mDependantParameters
;
1091 if ( count( $scriptDependantParams ) > 0 ) {
1092 $this->output( "Script dependant parameters:\n" );
1093 // Parameters description
1094 foreach ( $scriptDependantParams as $par => $info ) {
1095 if ( $info['shortName'] !== false ) {
1096 $par .= " (-{$info['shortName']})";
1099 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1100 "\n$tab$tab" ) . "\n"
1103 $this->output( "\n" );
1106 // Script specific parameters not defined on construction by
1107 // Maintenance::addDefaultParams()
1108 $scriptSpecificParams = array_diff_key(
1109 # all script parameters:
1111 # remove the Maintenance default parameters:
1112 $this->mGenericParameters
,
1113 $this->mDependantParameters
1115 if ( count( $scriptSpecificParams ) > 0 ) {
1116 $this->output( "Script specific parameters:\n" );
1117 // Parameters description
1118 foreach ( $scriptSpecificParams as $par => $info ) {
1119 if ( $info['shortName'] !== false ) {
1120 $par .= " (-{$info['shortName']})";
1123 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1124 "\n$tab$tab" ) . "\n"
1127 $this->output( "\n" );
1131 if ( count( $this->mArgList
) > 0 ) {
1132 $this->output( "Arguments:\n" );
1133 // Arguments description
1134 foreach ( $this->mArgList
as $info ) {
1135 $openChar = $info['require'] ?
'<' : '[';
1136 $closeChar = $info['require'] ?
'>' : ']';
1138 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1139 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1142 $this->output( "\n" );
1149 * Handle some last-minute setup here.
1151 public function finalSetup() {
1152 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1153 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1154 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1156 # Turn off output buffering again, it might have been turned on in the settings files
1157 if ( ob_get_level() ) {
1161 $wgCommandLineMode = true;
1163 # Override $wgServer
1164 if ( $this->hasOption( 'server' ) ) {
1165 $wgServer = $this->getOption( 'server', $wgServer );
1168 # If these were passed, use them
1169 if ( $this->mDbUser
) {
1170 $wgDBadminuser = $this->mDbUser
;
1172 if ( $this->mDbPass
) {
1173 $wgDBadminpassword = $this->mDbPass
;
1175 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1176 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1178 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1181 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1182 $wgDBuser = $wgDBadminuser;
1183 $wgDBpassword = $wgDBadminpassword;
1185 if ( $wgDBservers ) {
1187 * @var $wgDBservers array
1189 foreach ( $wgDBservers as $i => $server ) {
1190 $wgDBservers[$i]['user'] = $wgDBuser;
1191 $wgDBservers[$i]['password'] = $wgDBpassword;
1194 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1195 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1196 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1198 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1201 # Apply debug settings
1202 if ( $this->hasOption( 'mwdebug' ) ) {
1203 require __DIR__
. '/../includes/DevelopmentSettings.php';
1206 // Per-script profiling; useful for debugging
1207 $this->activateProfiler();
1209 $this->afterFinalSetup();
1211 $wgShowExceptionDetails = true;
1212 $wgShowHostnames = true;
1214 Wikimedia\
suppressWarnings();
1215 set_time_limit( 0 );
1216 Wikimedia\restoreWarnings
();
1218 $this->adjustMemoryLimit();
1222 * Execute a callback function at the end of initialisation
1224 protected function afterFinalSetup() {
1225 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1226 call_user_func( MW_CMDLINE_CALLBACK
);
1231 * Potentially debug globals. Originally a feature only
1234 public function globals() {
1235 if ( $this->hasOption( 'globals' ) ) {
1236 print_r( $GLOBALS );
1241 * Generic setup for most installs. Returns the location of LocalSettings
1244 public function loadSettings() {
1245 global $wgCommandLineMode, $IP;
1247 if ( isset( $this->mOptions
['conf'] ) ) {
1248 $settingsFile = $this->mOptions
['conf'];
1249 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1250 $settingsFile = MW_CONFIG_FILE
;
1252 $settingsFile = "$IP/LocalSettings.php";
1254 if ( isset( $this->mOptions
['wiki'] ) ) {
1255 $bits = explode( '-', $this->mOptions
['wiki'] );
1256 if ( count( $bits ) == 1 ) {
1259 define( 'MW_DB', $bits[0] );
1260 define( 'MW_PREFIX', $bits[1] );
1261 } elseif ( isset( $this->mOptions
['server'] ) ) {
1262 // Provide the option for site admins to detect and configure
1263 // multiple wikis based on server names. This offers --server
1264 // as alternative to --wiki.
1265 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1266 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1269 if ( !is_readable( $settingsFile ) ) {
1270 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1271 "must exist and be readable in the source directory.\n" .
1272 "Use --conf to specify it." );
1274 $wgCommandLineMode = true;
1276 return $settingsFile;
1280 * Support function for cleaning up redundant text records
1281 * @param bool $delete Whether or not to actually delete the records
1282 * @author Rob Church <robchur@gmail.com>
1284 public function purgeRedundantText( $delete = true ) {
1285 # Data should come off the master, wrapped in a transaction
1286 $dbw = $this->getDB( DB_MASTER
);
1287 $this->beginTransaction( $dbw, __METHOD__
);
1289 # Get "active" text records from the revisions table
1291 $this->output( 'Searching for active text records in revisions table...' );
1292 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1293 foreach ( $res as $row ) {
1294 $cur[] = $row->rev_text_id
;
1296 $this->output( "done.\n" );
1298 # Get "active" text records from the archive table
1299 $this->output( 'Searching for active text records in archive table...' );
1300 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1301 foreach ( $res as $row ) {
1302 # old pre-MW 1.5 records can have null ar_text_id's.
1303 if ( $row->ar_text_id
!== null ) {
1304 $cur[] = $row->ar_text_id
;
1307 $this->output( "done.\n" );
1309 # Get the IDs of all text records not in these sets
1310 $this->output( 'Searching for inactive text records...' );
1311 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1312 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1314 foreach ( $res as $row ) {
1315 $old[] = $row->old_id
;
1317 $this->output( "done.\n" );
1319 # Inform the user of what we're going to do
1320 $count = count( $old );
1321 $this->output( "$count inactive items found.\n" );
1323 # Delete as appropriate
1324 if ( $delete && $count ) {
1325 $this->output( 'Deleting...' );
1326 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1327 $this->output( "done.\n" );
1331 $this->commitTransaction( $dbw, __METHOD__
);
1335 * Get the maintenance directory.
1338 protected function getDir() {
1343 * Returns a database to be used by current maintenance script. It can be set by setDB().
1344 * If not set, wfGetDB() will be used.
1345 * This function has the same parameters as wfGetDB()
1347 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1348 * @param string|string[] $groups default: empty array
1349 * @param string|bool $wiki default: current wiki
1350 * @return IMaintainableDatabase
1352 protected function getDB( $db, $groups = [], $wiki = false ) {
1353 if ( is_null( $this->mDb
) ) {
1354 return wfGetDB( $db, $groups, $wiki );
1361 * Sets database object to be returned by getDB().
1363 * @param IDatabase $db
1365 public function setDB( IDatabase
$db ) {
1370 * Begin a transcation on a DB
1372 * This method makes it clear that begin() is called from a maintenance script,
1373 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1375 * @param IDatabase $dbw
1376 * @param string $fname Caller name
1379 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1380 $dbw->begin( $fname );
1384 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1386 * This method makes it clear that commit() is called from a maintenance script,
1387 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1389 * @param IDatabase $dbw
1390 * @param string $fname Caller name
1391 * @return bool Whether the replica DB wait succeeded
1394 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1395 $dbw->commit( $fname );
1397 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1398 $lbFactory->waitForReplication(
1399 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1401 $this->lastReplicationWait
= microtime( true );
1404 } catch ( DBReplicationWaitError
$e ) {
1410 * Rollback the transcation on a DB handle
1412 * This method makes it clear that rollback() is called from a maintenance script,
1413 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1415 * @param IDatabase $dbw
1416 * @param string $fname Caller name
1419 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1420 $dbw->rollback( $fname );
1424 * Lock the search index
1425 * @param IMaintainableDatabase &$db
1427 private function lockSearchindex( $db ) {
1428 $write = [ 'searchindex' ];
1438 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1443 * @param IMaintainableDatabase &$db
1445 private function unlockSearchindex( $db ) {
1446 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1450 * Unlock and lock again
1451 * Since the lock is low-priority, queued reads will be able to complete
1452 * @param IMaintainableDatabase &$db
1454 private function relockSearchindex( $db ) {
1455 $this->unlockSearchindex( $db );
1456 $this->lockSearchindex( $db );
1460 * Perform a search index update with locking
1461 * @param int $maxLockTime The maximum time to keep the search index locked.
1462 * @param string $callback The function that will update the function.
1463 * @param IMaintainableDatabase $dbw
1464 * @param array $results
1466 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1470 if ( $maxLockTime ) {
1471 $this->output( " --- Waiting for lock ---" );
1472 $this->lockSearchindex( $dbw );
1474 $this->output( "\n" );
1477 # Loop through the results and do a search update
1478 foreach ( $results as $row ) {
1479 # Allow reads to be processed
1480 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1481 $this->output( " --- Relocking ---" );
1482 $this->relockSearchindex( $dbw );
1484 $this->output( "\n" );
1486 call_user_func( $callback, $dbw, $row );
1489 # Unlock searchindex
1490 if ( $maxLockTime ) {
1491 $this->output( " --- Unlocking --" );
1492 $this->unlockSearchindex( $dbw );
1493 $this->output( "\n" );
1498 * Update the searchindex table for a given pageid
1499 * @param IDatabase $dbw A database write handle
1500 * @param int $pageId The page ID to update.
1501 * @return null|string
1503 public function updateSearchIndexForPage( $dbw, $pageId ) {
1504 // Get current revision
1505 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1508 $titleObj = $rev->getTitle();
1509 $title = $titleObj->getPrefixedDBkey();
1510 $this->output( "$title..." );
1511 # Update searchindex
1512 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1514 $this->output( "\n" );
1521 * Count down from $seconds to zero on the terminal, with a one-second pause
1522 * between showing each number. If the maintenance script is in quiet mode,
1523 * this function does nothing.
1527 * @codeCoverageIgnore
1528 * @param int $seconds
1530 protected function countDown( $seconds ) {
1531 if ( $this->isQuiet() ) {
1534 for ( $i = $seconds; $i >= 0; $i-- ) {
1535 if ( $i != $seconds ) {
1536 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1538 $this->output( $i );
1543 $this->output( "\n" );
1547 * Wrapper for posix_isatty()
1548 * We default as considering stdin a tty (for nice readline methods)
1549 * but treating stout as not a tty to avoid color codes
1551 * @param mixed $fd File descriptor
1554 public static function posix_isatty( $fd ) {
1555 if ( !function_exists( 'posix_isatty' ) ) {
1558 return posix_isatty( $fd );
1563 * Prompt the console for input
1564 * @param string $prompt What to begin the line with, like '> '
1565 * @return string Response
1567 public static function readconsole( $prompt = '> ' ) {
1568 static $isatty = null;
1569 if ( is_null( $isatty ) ) {
1570 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1573 if ( $isatty && function_exists( 'readline' ) ) {
1574 return readline( $prompt );
1577 $st = self
::readlineEmulation( $prompt );
1579 if ( feof( STDIN
) ) {
1582 $st = fgets( STDIN
, 1024 );
1585 if ( $st === false ) {
1588 $resp = trim( $st );
1595 * Emulate readline()
1596 * @param string $prompt What to begin the line with, like '> '
1599 private static function readlineEmulation( $prompt ) {
1600 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1601 if ( !wfIsWindows() && $bash ) {
1603 $encPrompt = wfEscapeShellArg( $prompt );
1604 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1605 $encCommand = wfEscapeShellArg( $command );
1606 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1608 if ( $retval == 0 ) {
1610 } elseif ( $retval == 127 ) {
1611 // Couldn't execute bash even though we thought we saw it.
1612 // Shell probably spit out an error message, sorry :(
1613 // Fall through to fgets()...
1620 // Fallback... we'll have no editing controls, EWWW
1621 if ( feof( STDIN
) ) {
1626 return fgets( STDIN
, 1024 );
1630 * Get the terminal size as a two-element array where the first element
1631 * is the width (number of columns) and the second element is the height
1636 public static function getTermSize() {
1637 $default = [ 80, 50 ];
1638 if ( wfIsWindows() ) {
1641 if ( Shell
::isDisabled() ) {
1644 // It's possible to get the screen size with VT-100 terminal escapes,
1645 // but reading the responses is not possible without setting raw mode
1646 // (unless you want to require the user to press enter), and that
1647 // requires an ioctl(), which we can't do. So we have to shell out to
1648 // something that can do the relevant syscalls. There are a few
1649 // options. Linux and Mac OS X both have "stty size" which does the
1651 $result = Shell
::command( 'stty', 'size' )
1653 if ( $result->getExitCode() !== 0 ) {
1656 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1659 return [ intval( $m[2] ), intval( $m[1] ) ];
1663 * Call this to set up the autoloader to allow classes to be used from the
1666 public static function requireTestsAutoloader() {
1667 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1672 * Fake maintenance wrapper, mostly used for the web installer/updater
1674 class FakeMaintenance
extends Maintenance
{
1675 protected $mSelf = "FakeMaintenanceScript";
1677 public function execute() {
1683 * Class for scripts that perform database maintenance and want to log the
1684 * update in `updatelog` so we can later skip it
1686 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1687 public function __construct() {
1688 parent
::__construct();
1689 $this->addOption( 'force', 'Run the update even if it was completed already' );
1690 $this->setBatchSize( 200 );
1693 public function execute() {
1694 $db = $this->getDB( DB_MASTER
);
1695 $key = $this->getUpdateKey();
1697 if ( !$this->hasOption( 'force' )
1698 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1700 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1705 if ( !$this->doDBUpdates() ) {
1709 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1712 $this->output( $this->updatelogFailedMessage() . "\n" );
1719 * Message to show that the update was done already and was just skipped
1722 protected function updateSkippedMessage() {
1723 $key = $this->getUpdateKey();
1725 return "Update '{$key}' already logged as completed.";
1729 * Message to show that the update log was unable to log the completion of this update
1732 protected function updatelogFailedMessage() {
1733 $key = $this->getUpdateKey();
1735 return "Unable to log update '{$key}' as completed.";
1739 * Do the actual work. All child classes will need to implement this.
1740 * Return true to log the update as done or false (usually on failure).
1743 abstract protected function doDBUpdates();
1746 * Get the update key name to go in the update log table
1749 abstract protected function getUpdateKey();