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( 'text' );
28 use MediaWiki\Shell\Shell
;
31 * @defgroup MaintenanceArchive Maintenance archives
32 * @ingroup Maintenance
35 // Define this so scripts can easily find doMaintenance.php
36 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
39 * @deprecated since 1.31
41 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
45 use Wikimedia\Rdbms\IDatabase
;
46 use MediaWiki\Logger\LoggerFactory
;
47 use MediaWiki\MediaWikiServices
;
48 use Wikimedia\Rdbms\LBFactory
;
49 use Wikimedia\Rdbms\IMaintainableDatabase
;
52 * Abstract maintenance class for quickly writing and churning out
53 * maintenance scripts with minimal effort. All that _must_ be defined
54 * is the execute() method. See docs/maintenance.txt for more info
55 * and a quick demo of how to use it.
58 * @ingroup Maintenance
60 abstract class Maintenance
{
62 * Constants for DB access type
63 * @see Maintenance::getDbType()
69 // Const for getStdin()
70 const STDIN_ALL
= 'all';
72 // This is the desired params
73 protected $mParams = [];
75 // Array of mapping short parameters to long ones
76 protected $mShortParamsMap = [];
78 // Array of desired args
79 protected $mArgList = [];
81 // This is the list of options that were actually passed
82 protected $mOptions = [];
84 // This is the list of arguments that were actually passed
85 protected $mArgs = [];
87 // Allow arbitrary options to be passed, or only specified ones?
88 protected $mAllowUnregisteredOptions = false;
90 // Name of the script currently running
93 // Special vars for params that are always used
94 protected $mQuiet = false;
95 protected $mDbUser, $mDbPass;
97 // A description of the script, children should change this via addDescription()
98 protected $mDescription = '';
100 // Have we already loaded our user input?
101 protected $mInputLoaded = false;
104 * Batch size. If a script supports this, they should set
105 * a default with setBatchSize()
109 protected $mBatchSize = null;
111 // Generic options added by addDefaultParams()
112 private $mGenericParameters = [];
113 // Generic options which might or not be supported by the script
114 private $mDependantParameters = [];
117 * Used by getDB() / setDB()
118 * @var IMaintainableDatabase
122 /** @var float UNIX timestamp */
123 private $lastReplicationWait = 0.0;
126 * Used when creating separate schema files.
132 * Accessible via getConfig()
139 * @see Maintenance::requireExtension
142 private $requiredExtensions = [];
145 * Used to read the options in the order they were passed.
146 * Useful for option chaining (Ex. dumpBackup.php). It will
147 * be an empty array if the options are passed in through
148 * loadParamsAndArgs( $self, $opts, $args ).
150 * This is an array of arrays where
151 * 0 => the option and 1 => parameter value.
155 public $orderedOptions = [];
158 * Default constructor. Children should call this *first* if implementing
159 * their own constructors
161 public function __construct() {
162 // Setup $IP, using MW_INSTALL_PATH if it exists
164 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
165 ?
getenv( 'MW_INSTALL_PATH' )
166 : realpath( __DIR__
. '/..' );
168 $this->addDefaultParams();
169 register_shutdown_function( [ $this, 'outputChanneled' ], false );
173 * Should we execute the maintenance script, or just allow it to be included
174 * as a standalone class? It checks that the call stack only includes this
175 * function and "requires" (meaning was called from the file scope)
179 public static function shouldExecute() {
180 global $wgCommandLineMode;
182 if ( !function_exists( 'debug_backtrace' ) ) {
183 // If someone has a better idea...
184 return $wgCommandLineMode;
187 $bt = debug_backtrace();
188 $count = count( $bt );
190 return false; // sanity
192 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
193 return false; // last call should be to this function
195 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
196 for ( $i = 1; $i < $count; $i++
) {
197 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
198 return false; // previous calls should all be "requires"
206 * Do the actual work. All child classes will need to implement this
208 * @return bool|null|void True for success, false for failure. Not returning
209 * a value, or returning null, is also interpreted as success. Returning
210 * false for failure will cause doMaintenance.php to exit the process
211 * with a non-zero exit status.
213 abstract public function execute();
216 * Checks to see if a particular option in supported. Normally this means it
217 * has been registered by the script via addOption.
218 * @param string $name The name of the option
219 * @return bool true if the option exists, false otherwise
221 protected function supportsOption( $name ) {
222 return isset( $this->mParams
[$name] );
226 * Add a parameter to the script. Will be displayed on --help
227 * with the associated description
229 * @param string $name The name of the param (help, version, etc)
230 * @param string $description The description of the param to show on --help
231 * @param bool $required Is the param required?
232 * @param bool $withArg Is an argument required with this option?
233 * @param string|bool $shortName Character to use as short name
234 * @param bool $multiOccurrence Can this option be passed multiple times?
236 protected function addOption( $name, $description, $required = false,
237 $withArg = false, $shortName = false, $multiOccurrence = false
239 $this->mParams
[$name] = [
240 'desc' => $description,
241 'require' => $required,
242 'withArg' => $withArg,
243 'shortName' => $shortName,
244 'multiOccurrence' => $multiOccurrence
247 if ( $shortName !== false ) {
248 $this->mShortParamsMap
[$shortName] = $name;
253 * Checks to see if a particular option exists.
254 * @param string $name The name of the option
257 protected function hasOption( $name ) {
258 return isset( $this->mOptions
[$name] );
262 * Get an option, or return the default.
264 * If the option was added to support multiple occurrences,
265 * this will return an array.
267 * @param string $name The name of the param
268 * @param mixed|null $default Anything you want, default null
271 protected function getOption( $name, $default = null ) {
272 if ( $this->hasOption( $name ) ) {
273 return $this->mOptions
[$name];
275 // Set it so we don't have to provide the default again
276 $this->mOptions
[$name] = $default;
278 return $this->mOptions
[$name];
283 * Add some args that are needed
284 * @param string $arg Name of the arg, like 'start'
285 * @param string $description Short description of the arg
286 * @param bool $required Is this required?
288 protected function addArg( $arg, $description, $required = true ) {
289 $this->mArgList
[] = [
291 'desc' => $description,
292 'require' => $required
297 * Remove an option. Useful for removing options that won't be used in your script.
298 * @param string $name The option to remove.
300 protected function deleteOption( $name ) {
301 unset( $this->mParams
[$name] );
305 * Sets whether to allow unregistered options, which are options passed to
306 * a script that do not match an expected parameter.
307 * @param bool $allow Should we allow?
309 protected function setAllowUnregisteredOptions( $allow ) {
310 $this->mAllowUnregisteredOptions
= $allow;
314 * Set the description text.
315 * @param string $text The text of the description
317 protected function addDescription( $text ) {
318 $this->mDescription
= $text;
322 * Does a given argument exist?
323 * @param int $argId The integer value (from zero) for the arg
326 protected function hasArg( $argId = 0 ) {
327 if ( func_num_args() === 0 ) {
328 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
331 return isset( $this->mArgs
[$argId] );
336 * @param int $argId The integer value (from zero) for the arg
337 * @param mixed|null $default The default if it doesn't exist
340 protected function getArg( $argId = 0, $default = null ) {
341 if ( func_num_args() === 0 ) {
342 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
345 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
355 protected function getBatchSize() {
356 return $this->mBatchSize
;
360 * Set the batch size.
361 * @param int $s The number of operations to do in a batch
363 protected function setBatchSize( $s = 0 ) {
364 $this->mBatchSize
= $s;
366 // If we support $mBatchSize, show the option.
367 // Used to be in addDefaultParams, but in order for that to
368 // work, subclasses would have to call this function in the constructor
369 // before they called parent::__construct which is just weird
370 // (and really wasn't done).
371 if ( $this->mBatchSize
) {
372 $this->addOption( 'batch-size', 'Run this many operations ' .
373 'per batch, default: ' . $this->mBatchSize
, false, true );
374 if ( isset( $this->mParams
['batch-size'] ) ) {
375 // This seems a little ugly...
376 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
382 * Get the script's name
385 public function getName() {
390 * Return input from stdin.
391 * @param int|null $len The number of bytes to read. If null, just return the handle.
392 * Maintenance::STDIN_ALL returns the full length
395 protected function getStdin( $len = null ) {
396 if ( $len == self
::STDIN_ALL
) {
397 return file_get_contents( 'php://stdin' );
399 $f = fopen( 'php://stdin', 'rt' );
403 $input = fgets( $f, $len );
406 return rtrim( $input );
412 public function isQuiet() {
413 return $this->mQuiet
;
417 * Throw some output to the user. Scripts can call this with no fears,
418 * as we handle all --quiet stuff here
419 * @param string $out The text to show to the user
420 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
422 protected function output( $out, $channel = null ) {
423 // This is sometimes called very early, before Setup.php is included.
424 if ( class_exists( MediaWikiServices
::class ) ) {
425 // Try to periodically flush buffered metrics to avoid OOMs
426 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
427 if ( $stats->getDataCount() > 1000 ) {
428 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
432 if ( $this->mQuiet
) {
435 if ( $channel === null ) {
436 $this->cleanupChanneled();
439 $out = preg_replace( '/\n\z/', '', $out );
440 $this->outputChanneled( $out, $channel );
445 * Throw an error to the user. Doesn't respect --quiet, so don't use
446 * this for non-error output
447 * @param string $err The error to display
448 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
450 protected function error( $err, $die = 0 ) {
451 if ( intval( $die ) !== 0 ) {
452 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
453 $this->fatalError( $err, intval( $die ) );
455 $this->outputChanneled( false );
457 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
458 !defined( 'MW_PHPUNIT_TEST' )
460 fwrite( STDERR
, $err . "\n" );
467 * Output a message and terminate the current script.
469 * @param string $msg Error message
470 * @param int $exitCode PHP exit status. Should be in range 1-254.
473 protected function fatalError( $msg, $exitCode = 1 ) {
474 $this->error( $msg );
478 private $atLineStart = true;
479 private $lastChannel = null;
482 * Clean up channeled output. Output a newline if necessary.
484 public function cleanupChanneled() {
485 if ( !$this->atLineStart
) {
487 $this->atLineStart
= true;
492 * Message outputter with channeled message support. Messages on the
493 * same channel are concatenated, but any intervening messages in another
494 * channel start a new line.
495 * @param string $msg The message without trailing newline
496 * @param string|null $channel Channel identifier or null for no
497 * channel. Channel comparison uses ===.
499 public function outputChanneled( $msg, $channel = null ) {
500 if ( $msg === false ) {
501 $this->cleanupChanneled();
506 // End the current line if necessary
507 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
513 $this->atLineStart
= false;
514 if ( $channel === null ) {
515 // For unchanneled messages, output trailing newline immediately
517 $this->atLineStart
= true;
519 $this->lastChannel
= $channel;
523 * Does the script need different DB access? By default, we give Maintenance
524 * scripts normal rights to the DB. Sometimes, a script needs admin rights
525 * access for a reason and sometimes they want no access. Subclasses should
526 * override and return one of the following values, as needed:
527 * Maintenance::DB_NONE - For no DB access at all
528 * Maintenance::DB_STD - For normal DB access, default
529 * Maintenance::DB_ADMIN - For admin DB access
532 public function getDbType() {
537 * Add the default parameters to the scripts
539 protected function addDefaultParams() {
540 # Generic (non script dependant) options:
542 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
543 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
544 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
545 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
546 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
549 'Set a specific memory limit for the script, '
550 . '"max" for no limit or "default" to avoid changing it',
554 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
555 "http://en.wikipedia.org. This is sometimes necessary because " .
556 "server name detection may fail in command line scripts.", false, true );
557 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
558 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
559 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
561 # Save generic options to display them separately in help
562 $this->mGenericParameters
= $this->mParams
;
564 # Script dependant options:
566 // If we support a DB, show the options
567 if ( $this->getDbType() > 0 ) {
568 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
569 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
570 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
573 # Save additional script dependant options to display
574 # Â them separately in help
575 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
582 public function getConfig() {
583 if ( $this->config
=== null ) {
584 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
587 return $this->config
;
592 * @param Config $config
594 public function setConfig( Config
$config ) {
595 $this->config
= $config;
599 * Indicate that the specified extension must be
600 * loaded before the script can run.
602 * This *must* be called in the constructor.
605 * @param string $name
607 protected function requireExtension( $name ) {
608 $this->requiredExtensions
[] = $name;
612 * Verify that the required extensions are installed
616 public function checkRequiredExtensions() {
617 $registry = ExtensionRegistry
::getInstance();
619 foreach ( $this->requiredExtensions
as $name ) {
620 if ( !$registry->isLoaded( $name ) ) {
626 $joined = implode( ', ', $missing );
627 $msg = "The following extensions are required to be installed "
628 . "for this script to run: $joined. Please enable them and then try again.";
629 $this->fatalError( $msg );
634 * Set triggers like when to try to run deferred updates
637 public function setAgentAndTriggers() {
638 if ( function_exists( 'posix_getpwuid' ) ) {
639 $agent = posix_getpwuid( posix_geteuid() )['name'];
643 $agent .= '@' . wfHostname();
645 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
646 // Add a comment for easy SHOW PROCESSLIST interpretation
647 $lbFactory->setAgentName(
648 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
650 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
654 * @param LBFactory $LBFactory
655 * @param Config $config
658 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
659 $services = MediaWikiServices
::getInstance();
660 $stats = $services->getStatsdDataFactory();
661 // Hook into period lag checks which often happen in long-running scripts
662 $lbFactory = $services->getDBLoadBalancerFactory();
663 $lbFactory->setWaitForReplicationListener(
665 function () use ( $stats, $config ) {
666 // Check config in case of JobRunner and unit tests
667 if ( $config->get( 'CommandLineMode' ) ) {
668 DeferredUpdates
::tryOpportunisticExecute( 'run' );
670 // Try to periodically flush buffered metrics to avoid OOMs
671 MediaWiki
::emitBufferedStatsdData( $stats, $config );
674 // Check for other windows to run them. A script may read or do a few writes
675 // to the master but mostly be writing to something else, like a file store.
676 $lbFactory->getMainLB()->setTransactionListener(
678 function ( $trigger ) use ( $stats, $config ) {
679 // Check config in case of JobRunner and unit tests
680 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
681 DeferredUpdates
::tryOpportunisticExecute( 'run' );
683 // Try to periodically flush buffered metrics to avoid OOMs
684 MediaWiki
::emitBufferedStatsdData( $stats, $config );
690 * Run a child maintenance script. Pass all of the current arguments
692 * @param string $maintClass A name of a child maintenance class
693 * @param string|null $classFile Full path of where the child is
694 * @return Maintenance
696 public function runChild( $maintClass, $classFile = null ) {
697 // Make sure the class is loaded first
698 if ( !class_exists( $maintClass ) ) {
700 require_once $classFile;
702 if ( !class_exists( $maintClass ) ) {
703 $this->error( "Cannot spawn child: $maintClass" );
708 * @var $child Maintenance
710 $child = new $maintClass();
711 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
712 if ( !is_null( $this->mDb
) ) {
713 $child->setDB( $this->mDb
);
720 * Do some sanity checking and basic setup
722 public function setup() {
723 global $IP, $wgCommandLineMode;
725 # Abort if called from a web server
726 # wfIsCLI() is not available yet
727 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
728 $this->fatalError( 'This script must be run from the command line' );
731 if ( $IP === null ) {
732 $this->fatalError( "\$IP not set, aborting!\n" .
733 '(Did you forget to call parent::__construct() in your maintenance script?)' );
736 # Make sure we can handle script parameters
737 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
738 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
741 // Send PHP warnings and errors to stderr instead of stdout.
742 // This aids in diagnosing problems, while keeping messages
743 // out of redirected output.
744 if ( ini_get( 'display_errors' ) ) {
745 ini_set( 'display_errors', 'stderr' );
748 $this->loadParamsAndArgs();
751 # Set the memory limit
752 # Note we need to set it again later in cache LocalSettings changed it
753 $this->adjustMemoryLimit();
755 # Set max execution time to 0 (no limit). PHP.net says that
756 # "When running PHP from the command line the default setting is 0."
757 # But sometimes this doesn't seem to be the case.
758 ini_set( 'max_execution_time', 0 );
760 # Define us as being in MediaWiki
761 define( 'MEDIAWIKI', true );
763 $wgCommandLineMode = true;
765 # Turn off output buffering if it's on
766 while ( ob_get_level() > 0 ) {
770 $this->validateParamsAndArgs();
774 * Normally we disable the memory_limit when running admin scripts.
775 * Some scripts may wish to actually set a limit, however, to avoid
776 * blowing up unexpectedly. We also support a --memory-limit option,
777 * to allow sysadmins to explicitly set one if they'd prefer to override
778 * defaults (or for people using Suhosin which yells at you for trying
779 * to disable the limits)
782 public function memoryLimit() {
783 $limit = $this->getOption( 'memory-limit', 'max' );
784 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
789 * Adjusts PHP's memory limit to better suit our needs, if needed.
791 protected function adjustMemoryLimit() {
792 $limit = $this->memoryLimit();
793 if ( $limit == 'max' ) {
794 $limit = -1; // no memory limit
796 if ( $limit != 'default' ) {
797 ini_set( 'memory_limit', $limit );
802 * Activate the profiler (assuming $wgProfiler is set)
804 protected function activateProfiler() {
805 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
807 $output = $this->getOption( 'profiler' );
812 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
813 $class = $wgProfiler['class'];
814 /** @var Profiler $profiler */
815 $profiler = new $class(
816 [ 'sampling' => 1, 'output' => [ $output ] ]
818 +
[ 'threshold' => $wgProfileLimit ]
820 $profiler->setTemplated( true );
821 Profiler
::replaceStubInstance( $profiler );
824 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
825 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
826 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
830 * Clear all params and arguments.
832 public function clearParamsAndArgs() {
833 $this->mOptions
= [];
835 $this->mInputLoaded
= false;
839 * Load params and arguments from a given array
840 * of command-line arguments
845 public function loadWithArgv( $argv ) {
848 $this->orderedOptions
= [];
851 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
852 if ( $arg == '--' ) {
853 # End of options, remainder should be considered arguments
854 $arg = next( $argv );
855 while ( $arg !== false ) {
857 $arg = next( $argv );
860 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
862 $option = substr( $arg, 2 );
863 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
864 $param = next( $argv );
865 if ( $param === false ) {
866 $this->error( "\nERROR: $option parameter needs a value after it\n" );
867 $this->maybeHelp( true );
870 $this->setParam( $options, $option, $param );
872 $bits = explode( '=', $option, 2 );
873 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
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'], 2 );
1256 define( 'MW_DB', $bits[0] );
1257 define( 'MW_PREFIX', $bits[1] ??
'' );
1258 } elseif ( isset( $this->mOptions
['server'] ) ) {
1259 // Provide the option for site admins to detect and configure
1260 // multiple wikis based on server names. This offers --server
1261 // as alternative to --wiki.
1262 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1263 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1266 if ( !is_readable( $settingsFile ) ) {
1267 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1268 "must exist and be readable in the source directory.\n" .
1269 "Use --conf to specify it." );
1271 $wgCommandLineMode = true;
1273 return $settingsFile;
1277 * Support function for cleaning up redundant text records
1278 * @param bool $delete Whether or not to actually delete the records
1279 * @author Rob Church <robchur@gmail.com>
1281 public function purgeRedundantText( $delete = true ) {
1282 global $wgMultiContentRevisionSchemaMigrationStage;
1284 # Data should come off the master, wrapped in a transaction
1285 $dbw = $this->getDB( DB_MASTER
);
1286 $this->beginTransaction( $dbw, __METHOD__
);
1288 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
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 "active" text records via the content table
1311 $this->output( 'Searching for active text records via contents table...' );
1312 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1313 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1314 foreach ( $res as $row ) {
1315 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1320 $this->output( "done.\n" );
1322 $this->output( "done.\n" );
1324 # Get the IDs of all text records not in these sets
1325 $this->output( 'Searching for inactive text records...' );
1326 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1327 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1329 foreach ( $res as $row ) {
1330 $old[] = $row->old_id
;
1332 $this->output( "done.\n" );
1334 # Inform the user of what we're going to do
1335 $count = count( $old );
1336 $this->output( "$count inactive items found.\n" );
1338 # Delete as appropriate
1339 if ( $delete && $count ) {
1340 $this->output( 'Deleting...' );
1341 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1342 $this->output( "done.\n" );
1345 $this->commitTransaction( $dbw, __METHOD__
);
1349 * Get the maintenance directory.
1352 protected function getDir() {
1357 * Returns a database to be used by current maintenance script. It can be set by setDB().
1358 * If not set, wfGetDB() will be used.
1359 * This function has the same parameters as wfGetDB()
1361 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1362 * @param string|string[] $groups default: empty array
1363 * @param string|bool $wiki default: current wiki
1364 * @return IMaintainableDatabase
1366 protected function getDB( $db, $groups = [], $wiki = false ) {
1367 if ( $this->mDb
=== null ) {
1368 return wfGetDB( $db, $groups, $wiki );
1374 * Sets database object to be returned by getDB().
1376 * @param IDatabase $db
1378 public function setDB( IDatabase
$db ) {
1383 * Begin a transcation on a DB
1385 * This method makes it clear that begin() is called from a maintenance script,
1386 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1388 * @param IDatabase $dbw
1389 * @param string $fname Caller name
1392 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1393 $dbw->begin( $fname );
1397 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1399 * This method makes it clear that commit() is called from a maintenance script,
1400 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1402 * @param IDatabase $dbw
1403 * @param string $fname Caller name
1404 * @return bool Whether the replica DB wait succeeded
1407 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1408 $dbw->commit( $fname );
1409 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1410 $waitSucceeded = $lbFactory->waitForReplication(
1411 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1413 $this->lastReplicationWait
= microtime( true );
1414 return $waitSucceeded;
1418 * Rollback the transcation on a DB handle
1420 * This method makes it clear that rollback() is called from a maintenance script,
1421 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1423 * @param IDatabase $dbw
1424 * @param string $fname Caller name
1427 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1428 $dbw->rollback( $fname );
1432 * Lock the search index
1433 * @param IMaintainableDatabase &$db
1435 private function lockSearchindex( $db ) {
1436 $write = [ 'searchindex' ];
1446 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1451 * @param IMaintainableDatabase &$db
1453 private function unlockSearchindex( $db ) {
1454 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1458 * Unlock and lock again
1459 * Since the lock is low-priority, queued reads will be able to complete
1460 * @param IMaintainableDatabase &$db
1462 private function relockSearchindex( $db ) {
1463 $this->unlockSearchindex( $db );
1464 $this->lockSearchindex( $db );
1468 * Perform a search index update with locking
1469 * @param int $maxLockTime The maximum time to keep the search index locked.
1470 * @param string $callback The function that will update the function.
1471 * @param IMaintainableDatabase $dbw
1472 * @param array $results
1474 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1478 if ( $maxLockTime ) {
1479 $this->output( " --- Waiting for lock ---" );
1480 $this->lockSearchindex( $dbw );
1482 $this->output( "\n" );
1485 # Loop through the results and do a search update
1486 foreach ( $results as $row ) {
1487 # Allow reads to be processed
1488 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1489 $this->output( " --- Relocking ---" );
1490 $this->relockSearchindex( $dbw );
1492 $this->output( "\n" );
1494 call_user_func( $callback, $dbw, $row );
1497 # Unlock searchindex
1498 if ( $maxLockTime ) {
1499 $this->output( " --- Unlocking --" );
1500 $this->unlockSearchindex( $dbw );
1501 $this->output( "\n" );
1506 * Update the searchindex table for a given pageid
1507 * @param IDatabase $dbw A database write handle
1508 * @param int $pageId The page ID to update.
1509 * @return null|string
1511 public function updateSearchIndexForPage( $dbw, $pageId ) {
1512 // Get current revision
1513 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1516 $titleObj = $rev->getTitle();
1517 $title = $titleObj->getPrefixedDBkey();
1518 $this->output( "$title..." );
1519 # Update searchindex
1520 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1522 $this->output( "\n" );
1529 * Count down from $seconds to zero on the terminal, with a one-second pause
1530 * between showing each number. If the maintenance script is in quiet mode,
1531 * this function does nothing.
1535 * @codeCoverageIgnore
1536 * @param int $seconds
1538 protected function countDown( $seconds ) {
1539 if ( $this->isQuiet() ) {
1542 for ( $i = $seconds; $i >= 0; $i-- ) {
1543 if ( $i != $seconds ) {
1544 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1546 $this->output( $i );
1551 $this->output( "\n" );
1555 * Wrapper for posix_isatty()
1556 * We default as considering stdin a tty (for nice readline methods)
1557 * but treating stout as not a tty to avoid color codes
1559 * @param mixed $fd File descriptor
1562 public static function posix_isatty( $fd ) {
1563 if ( !function_exists( 'posix_isatty' ) ) {
1566 return posix_isatty( $fd );
1571 * Prompt the console for input
1572 * @param string $prompt What to begin the line with, like '> '
1573 * @return string Response
1575 public static function readconsole( $prompt = '> ' ) {
1576 static $isatty = null;
1577 if ( is_null( $isatty ) ) {
1578 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1581 if ( $isatty && function_exists( 'readline' ) ) {
1582 return readline( $prompt );
1585 $st = self
::readlineEmulation( $prompt );
1587 if ( feof( STDIN
) ) {
1590 $st = fgets( STDIN
, 1024 );
1593 if ( $st === false ) {
1596 $resp = trim( $st );
1603 * Emulate readline()
1604 * @param string $prompt What to begin the line with, like '> '
1607 private static function readlineEmulation( $prompt ) {
1608 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1609 if ( !wfIsWindows() && $bash ) {
1611 $encPrompt = wfEscapeShellArg( $prompt );
1612 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1613 $encCommand = wfEscapeShellArg( $command );
1614 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1616 if ( $retval == 0 ) {
1618 } elseif ( $retval == 127 ) {
1619 // Couldn't execute bash even though we thought we saw it.
1620 // Shell probably spit out an error message, sorry :(
1621 // Fall through to fgets()...
1628 // Fallback... we'll have no editing controls, EWWW
1629 if ( feof( STDIN
) ) {
1634 return fgets( STDIN
, 1024 );
1638 * Get the terminal size as a two-element array where the first element
1639 * is the width (number of columns) and the second element is the height
1644 public static function getTermSize() {
1645 $default = [ 80, 50 ];
1646 if ( wfIsWindows() ) {
1649 if ( Shell
::isDisabled() ) {
1652 // It's possible to get the screen size with VT-100 terminal escapes,
1653 // but reading the responses is not possible without setting raw mode
1654 // (unless you want to require the user to press enter), and that
1655 // requires an ioctl(), which we can't do. So we have to shell out to
1656 // something that can do the relevant syscalls. There are a few
1657 // options. Linux and Mac OS X both have "stty size" which does the
1659 $result = Shell
::command( 'stty', 'size' )
1661 if ( $result->getExitCode() !== 0 ) {
1664 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1667 return [ intval( $m[2] ), intval( $m[1] ) ];
1671 * Call this to set up the autoloader to allow classes to be used from the
1674 public static function requireTestsAutoloader() {
1675 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1680 * Fake maintenance wrapper, mostly used for the web installer/updater
1682 class FakeMaintenance
extends Maintenance
{
1683 protected $mSelf = "FakeMaintenanceScript";
1685 public function execute() {
1690 * Class for scripts that perform database maintenance and want to log the
1691 * update in `updatelog` so we can later skip it
1693 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1694 public function __construct() {
1695 parent
::__construct();
1696 $this->addOption( 'force', 'Run the update even if it was completed already' );
1697 $this->setBatchSize( 200 );
1700 public function execute() {
1701 $db = $this->getDB( DB_MASTER
);
1702 $key = $this->getUpdateKey();
1704 if ( !$this->hasOption( 'force' )
1705 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1707 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1712 if ( !$this->doDBUpdates() ) {
1716 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' );
1722 * Message to show that the update was done already and was just skipped
1725 protected function updateSkippedMessage() {
1726 $key = $this->getUpdateKey();
1728 return "Update '{$key}' already logged as completed.";
1732 * Do the actual work. All child classes will need to implement this.
1733 * Return true to log the update as done or false (usually on failure).
1736 abstract protected function doDBUpdates();
1739 * Get the update key name to go in the update log table
1742 abstract protected function getUpdateKey();