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 * params: registry of named values that may be passed to the script
59 * arg list: registry of positional values that may be passed to the script
60 * options: passed param values
61 * args: passed positional values
64 * mwscript somescript.php --foo=bar baz
66 * bar is the option value of the option for param foo
67 * baz is the arg value at index 0 in the arg list
70 * @ingroup Maintenance
72 abstract class Maintenance
{
74 * Constants for DB access type
75 * @see Maintenance::getDbType()
81 // Const for getStdin()
82 const STDIN_ALL
= 'all';
84 // Array of desired/allowed params
85 protected $mParams = [];
87 // Array of mapping short parameters to long ones
88 protected $mShortParamsMap = [];
90 // Array of desired/allowed args
91 protected $mArgList = [];
93 // This is the list of options that were actually passed
94 protected $mOptions = [];
96 // This is the list of arguments that were actually passed
97 protected $mArgs = [];
99 // Allow arbitrary options to be passed, or only specified ones?
100 protected $mAllowUnregisteredOptions = false;
102 // Name of the script currently running
105 // Special vars for params that are always used
106 protected $mQuiet = false;
107 protected $mDbUser, $mDbPass;
109 // A description of the script, children should change this via addDescription()
110 protected $mDescription = '';
112 // Have we already loaded our user input?
113 protected $mInputLoaded = false;
116 * Batch size. If a script supports this, they should set
117 * a default with setBatchSize()
121 protected $mBatchSize = null;
123 // Generic options added by addDefaultParams()
124 private $mGenericParameters = [];
125 // Generic options which might or not be supported by the script
126 private $mDependantParameters = [];
129 * Used by getDB() / setDB()
130 * @var IMaintainableDatabase
134 /** @var float UNIX timestamp */
135 private $lastReplicationWait = 0.0;
138 * Used when creating separate schema files.
144 * Accessible via getConfig()
151 * @see Maintenance::requireExtension
154 private $requiredExtensions = [];
157 * Used to read the options in the order they were passed.
158 * Useful for option chaining (Ex. dumpBackup.php). It will
159 * be an empty array if the options are passed in through
160 * loadParamsAndArgs( $self, $opts, $args ).
162 * This is an array of arrays where
163 * 0 => the option and 1 => parameter value.
167 public $orderedOptions = [];
170 * Default constructor. Children should call this *first* if implementing
171 * their own constructors
173 public function __construct() {
174 // Setup $IP, using MW_INSTALL_PATH if it exists
176 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
177 ?
getenv( 'MW_INSTALL_PATH' )
178 : realpath( __DIR__
. '/..' );
180 $this->addDefaultParams();
181 register_shutdown_function( [ $this, 'outputChanneled' ], false );
185 * Should we execute the maintenance script, or just allow it to be included
186 * as a standalone class? It checks that the call stack only includes this
187 * function and "requires" (meaning was called from the file scope)
191 public static function shouldExecute() {
192 global $wgCommandLineMode;
194 if ( !function_exists( 'debug_backtrace' ) ) {
195 // If someone has a better idea...
196 return $wgCommandLineMode;
199 $bt = debug_backtrace();
200 $count = count( $bt );
202 return false; // sanity
204 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
205 return false; // last call should be to this function
207 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
208 for ( $i = 1; $i < $count; $i++
) {
209 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
210 return false; // previous calls should all be "requires"
218 * Do the actual work. All child classes will need to implement this
220 * @return bool|null|void True for success, false for failure. Not returning
221 * a value, or returning null, is also interpreted as success. Returning
222 * false for failure will cause doMaintenance.php to exit the process
223 * with a non-zero exit status.
225 abstract public function execute();
228 * Checks to see if a particular option in supported. Normally this means it
229 * has been registered by the script via addOption.
230 * @param string $name The name of the option
231 * @return bool true if the option exists, false otherwise
233 protected function supportsOption( $name ) {
234 return isset( $this->mParams
[$name] );
238 * Add a parameter to the script. Will be displayed on --help
239 * with the associated description
241 * @param string $name The name of the param (help, version, etc)
242 * @param string $description The description of the param to show on --help
243 * @param bool $required Is the param required?
244 * @param bool $withArg Is an argument required with this option?
245 * @param string|bool $shortName Character to use as short name
246 * @param bool $multiOccurrence Can this option be passed multiple times?
248 protected function addOption( $name, $description, $required = false,
249 $withArg = false, $shortName = false, $multiOccurrence = false
251 $this->mParams
[$name] = [
252 'desc' => $description,
253 'require' => $required,
254 'withArg' => $withArg,
255 'shortName' => $shortName,
256 'multiOccurrence' => $multiOccurrence
259 if ( $shortName !== false ) {
260 $this->mShortParamsMap
[$shortName] = $name;
265 * Checks to see if a particular option exists.
266 * @param string $name The name of the option
269 protected function hasOption( $name ) {
270 return isset( $this->mOptions
[$name] );
274 * Get an option, or return the default.
276 * If the option was added to support multiple occurrences,
277 * this will return an array.
279 * @param string $name The name of the param
280 * @param mixed|null $default Anything you want, default null
283 protected function getOption( $name, $default = null ) {
284 if ( $this->hasOption( $name ) ) {
285 return $this->mOptions
[$name];
287 // Set it so we don't have to provide the default again
288 $this->mOptions
[$name] = $default;
290 return $this->mOptions
[$name];
295 * Add some args that are needed
296 * @param string $arg Name of the arg, like 'start'
297 * @param string $description Short description of the arg
298 * @param bool $required Is this required?
300 protected function addArg( $arg, $description, $required = true ) {
301 $this->mArgList
[] = [
303 'desc' => $description,
304 'require' => $required
309 * Remove an option. Useful for removing options that won't be used in your script.
310 * @param string $name The option to remove.
312 protected function deleteOption( $name ) {
313 unset( $this->mParams
[$name] );
317 * Sets whether to allow unregistered options, which are options passed to
318 * a script that do not match an expected parameter.
319 * @param bool $allow Should we allow?
321 protected function setAllowUnregisteredOptions( $allow ) {
322 $this->mAllowUnregisteredOptions
= $allow;
326 * Set the description text.
327 * @param string $text The text of the description
329 protected function addDescription( $text ) {
330 $this->mDescription
= $text;
334 * Does a given argument exist?
335 * @param int $argId The integer value (from zero) for the arg
338 protected function hasArg( $argId = 0 ) {
339 if ( func_num_args() === 0 ) {
340 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
343 return isset( $this->mArgs
[$argId] );
348 * @param int $argId The integer value (from zero) for the arg
349 * @param mixed|null $default The default if it doesn't exist
352 protected function getArg( $argId = 0, $default = null ) {
353 if ( func_num_args() === 0 ) {
354 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
357 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
367 protected function getBatchSize() {
368 return $this->mBatchSize
;
372 * Set the batch size.
373 * @param int $s The number of operations to do in a batch
375 protected function setBatchSize( $s = 0 ) {
376 $this->mBatchSize
= $s;
378 // If we support $mBatchSize, show the option.
379 // Used to be in addDefaultParams, but in order for that to
380 // work, subclasses would have to call this function in the constructor
381 // before they called parent::__construct which is just weird
382 // (and really wasn't done).
383 if ( $this->mBatchSize
) {
384 $this->addOption( 'batch-size', 'Run this many operations ' .
385 'per batch, default: ' . $this->mBatchSize
, false, true );
386 if ( isset( $this->mParams
['batch-size'] ) ) {
387 // This seems a little ugly...
388 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
394 * Get the script's name
397 public function getName() {
402 * Return input from stdin.
403 * @param int|null $len The number of bytes to read. If null, just return the handle.
404 * Maintenance::STDIN_ALL returns the full length
407 protected function getStdin( $len = null ) {
408 if ( $len == self
::STDIN_ALL
) {
409 return file_get_contents( 'php://stdin' );
411 $f = fopen( 'php://stdin', 'rt' );
415 $input = fgets( $f, $len );
418 return rtrim( $input );
424 public function isQuiet() {
425 return $this->mQuiet
;
429 * Throw some output to the user. Scripts can call this with no fears,
430 * as we handle all --quiet stuff here
431 * @param string $out The text to show to the user
432 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
434 protected function output( $out, $channel = null ) {
435 // This is sometimes called very early, before Setup.php is included.
436 if ( class_exists( MediaWikiServices
::class ) ) {
437 // Try to periodically flush buffered metrics to avoid OOMs
438 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
439 if ( $stats->getDataCount() > 1000 ) {
440 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
444 if ( $this->mQuiet
) {
447 if ( $channel === null ) {
448 $this->cleanupChanneled();
451 $out = preg_replace( '/\n\z/', '', $out );
452 $this->outputChanneled( $out, $channel );
457 * Throw an error to the user. Doesn't respect --quiet, so don't use
458 * this for non-error output
459 * @param string $err The error to display
460 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
462 protected function error( $err, $die = 0 ) {
463 if ( intval( $die ) !== 0 ) {
464 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
465 $this->fatalError( $err, intval( $die ) );
467 $this->outputChanneled( false );
469 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
470 !defined( 'MW_PHPUNIT_TEST' )
472 fwrite( STDERR
, $err . "\n" );
479 * Output a message and terminate the current script.
481 * @param string $msg Error message
482 * @param int $exitCode PHP exit status. Should be in range 1-254.
485 protected function fatalError( $msg, $exitCode = 1 ) {
486 $this->error( $msg );
490 private $atLineStart = true;
491 private $lastChannel = null;
494 * Clean up channeled output. Output a newline if necessary.
496 public function cleanupChanneled() {
497 if ( !$this->atLineStart
) {
499 $this->atLineStart
= true;
504 * Message outputter with channeled message support. Messages on the
505 * same channel are concatenated, but any intervening messages in another
506 * channel start a new line.
507 * @param string $msg The message without trailing newline
508 * @param string|null $channel Channel identifier or null for no
509 * channel. Channel comparison uses ===.
511 public function outputChanneled( $msg, $channel = null ) {
512 if ( $msg === false ) {
513 $this->cleanupChanneled();
518 // End the current line if necessary
519 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
525 $this->atLineStart
= false;
526 if ( $channel === null ) {
527 // For unchanneled messages, output trailing newline immediately
529 $this->atLineStart
= true;
531 $this->lastChannel
= $channel;
535 * Does the script need different DB access? By default, we give Maintenance
536 * scripts normal rights to the DB. Sometimes, a script needs admin rights
537 * access for a reason and sometimes they want no access. Subclasses should
538 * override and return one of the following values, as needed:
539 * Maintenance::DB_NONE - For no DB access at all
540 * Maintenance::DB_STD - For normal DB access, default
541 * Maintenance::DB_ADMIN - For admin DB access
544 public function getDbType() {
549 * Add the default parameters to the scripts
551 protected function addDefaultParams() {
552 # Generic (non script dependant) options:
554 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
555 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
556 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
557 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
558 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
561 'Set a specific memory limit for the script, '
562 . '"max" for no limit or "default" to avoid changing it',
566 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
567 "http://en.wikipedia.org. This is sometimes necessary because " .
568 "server name detection may fail in command line scripts.", false, true );
569 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
570 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
571 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
573 # Save generic options to display them separately in help
574 $this->mGenericParameters
= $this->mParams
;
576 # Script dependant options:
578 // If we support a DB, show the options
579 if ( $this->getDbType() > 0 ) {
580 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
581 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
582 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
585 # Save additional script dependant options to display
586 # Â them separately in help
587 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
594 public function getConfig() {
595 if ( $this->config
=== null ) {
596 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
599 return $this->config
;
604 * @param Config $config
606 public function setConfig( Config
$config ) {
607 $this->config
= $config;
611 * Indicate that the specified extension must be
612 * loaded before the script can run.
614 * This *must* be called in the constructor.
617 * @param string $name
619 protected function requireExtension( $name ) {
620 $this->requiredExtensions
[] = $name;
624 * Verify that the required extensions are installed
628 public function checkRequiredExtensions() {
629 $registry = ExtensionRegistry
::getInstance();
631 foreach ( $this->requiredExtensions
as $name ) {
632 if ( !$registry->isLoaded( $name ) ) {
638 $joined = implode( ', ', $missing );
639 $msg = "The following extensions are required to be installed "
640 . "for this script to run: $joined. Please enable them and then try again.";
641 $this->fatalError( $msg );
646 * Set triggers like when to try to run deferred updates
649 public function setAgentAndTriggers() {
650 if ( function_exists( 'posix_getpwuid' ) ) {
651 $agent = posix_getpwuid( posix_geteuid() )['name'];
655 $agent .= '@' . wfHostname();
657 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
658 // Add a comment for easy SHOW PROCESSLIST interpretation
659 $lbFactory->setAgentName(
660 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
662 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
666 * @param LBFactory $LBFactory
667 * @param Config $config
670 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
671 $services = MediaWikiServices
::getInstance();
672 $stats = $services->getStatsdDataFactory();
673 // Hook into period lag checks which often happen in long-running scripts
674 $lbFactory = $services->getDBLoadBalancerFactory();
675 $lbFactory->setWaitForReplicationListener(
677 function () use ( $stats, $config ) {
678 // Check config in case of JobRunner and unit tests
679 if ( $config->get( 'CommandLineMode' ) ) {
680 DeferredUpdates
::tryOpportunisticExecute( 'run' );
682 // Try to periodically flush buffered metrics to avoid OOMs
683 MediaWiki
::emitBufferedStatsdData( $stats, $config );
686 // Check for other windows to run them. A script may read or do a few writes
687 // to the master but mostly be writing to something else, like a file store.
688 $lbFactory->getMainLB()->setTransactionListener(
690 function ( $trigger ) use ( $stats, $config ) {
691 // Check config in case of JobRunner and unit tests
692 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
693 DeferredUpdates
::tryOpportunisticExecute( 'run' );
695 // Try to periodically flush buffered metrics to avoid OOMs
696 MediaWiki
::emitBufferedStatsdData( $stats, $config );
702 * Run a child maintenance script. Pass all of the current arguments
704 * @param string $maintClass A name of a child maintenance class
705 * @param string|null $classFile Full path of where the child is
706 * @return Maintenance
708 public function runChild( $maintClass, $classFile = null ) {
709 // Make sure the class is loaded first
710 if ( !class_exists( $maintClass ) ) {
712 require_once $classFile;
714 if ( !class_exists( $maintClass ) ) {
715 $this->error( "Cannot spawn child: $maintClass" );
720 * @var $child Maintenance
722 $child = new $maintClass();
723 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
724 if ( !is_null( $this->mDb
) ) {
725 $child->setDB( $this->mDb
);
732 * Do some sanity checking and basic setup
734 public function setup() {
735 global $IP, $wgCommandLineMode;
737 # Abort if called from a web server
738 # wfIsCLI() is not available yet
739 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
740 $this->fatalError( 'This script must be run from the command line' );
743 if ( $IP === null ) {
744 $this->fatalError( "\$IP not set, aborting!\n" .
745 '(Did you forget to call parent::__construct() in your maintenance script?)' );
748 # Make sure we can handle script parameters
749 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
750 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
753 // Send PHP warnings and errors to stderr instead of stdout.
754 // This aids in diagnosing problems, while keeping messages
755 // out of redirected output.
756 if ( ini_get( 'display_errors' ) ) {
757 ini_set( 'display_errors', 'stderr' );
760 $this->loadParamsAndArgs();
762 # Set the memory limit
763 # Note we need to set it again later in cache LocalSettings changed it
764 $this->adjustMemoryLimit();
766 # Set max execution time to 0 (no limit). PHP.net says that
767 # "When running PHP from the command line the default setting is 0."
768 # But sometimes this doesn't seem to be the case.
769 ini_set( 'max_execution_time', 0 );
771 # Define us as being in MediaWiki
772 define( 'MEDIAWIKI', true );
774 $wgCommandLineMode = true;
776 # Turn off output buffering if it's on
777 while ( ob_get_level() > 0 ) {
783 * Normally we disable the memory_limit when running admin scripts.
784 * Some scripts may wish to actually set a limit, however, to avoid
785 * blowing up unexpectedly. We also support a --memory-limit option,
786 * to allow sysadmins to explicitly set one if they'd prefer to override
787 * defaults (or for people using Suhosin which yells at you for trying
788 * to disable the limits)
791 public function memoryLimit() {
792 $limit = $this->getOption( 'memory-limit', 'max' );
793 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
798 * Adjusts PHP's memory limit to better suit our needs, if needed.
800 protected function adjustMemoryLimit() {
801 $limit = $this->memoryLimit();
802 if ( $limit == 'max' ) {
803 $limit = -1; // no memory limit
805 if ( $limit != 'default' ) {
806 ini_set( 'memory_limit', $limit );
811 * Activate the profiler (assuming $wgProfiler is set)
813 protected function activateProfiler() {
814 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
816 $output = $this->getOption( 'profiler' );
821 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
822 $class = $wgProfiler['class'];
823 /** @var Profiler $profiler */
824 $profiler = new $class(
825 [ 'sampling' => 1, 'output' => [ $output ] ]
827 +
[ 'threshold' => $wgProfileLimit ]
829 $profiler->setTemplated( true );
830 Profiler
::replaceStubInstance( $profiler );
833 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
834 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
835 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
839 * Clear all params and arguments.
841 public function clearParamsAndArgs() {
842 $this->mOptions
= [];
844 $this->mInputLoaded
= false;
848 * Load params and arguments from a given array
849 * of command-line arguments
854 public function loadWithArgv( $argv ) {
857 $this->orderedOptions
= [];
860 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
861 if ( $arg == '--' ) {
862 # End of options, remainder should be considered arguments
863 $arg = next( $argv );
864 while ( $arg !== false ) {
866 $arg = next( $argv );
869 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
871 $option = substr( $arg, 2 );
872 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
873 $param = next( $argv );
874 if ( $param === false ) {
875 $this->error( "\nERROR: $option parameter needs a value after it\n" );
876 $this->maybeHelp( true );
879 $this->setParam( $options, $option, $param );
881 $bits = explode( '=', $option, 2 );
882 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
884 } elseif ( $arg == '-' ) {
885 # Lonely "-", often used to indicate stdin or stdout.
887 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
889 $argLength = strlen( $arg );
890 for ( $p = 1; $p < $argLength; $p++
) {
892 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
893 $option = $this->mShortParamsMap
[$option];
896 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
897 $param = next( $argv );
898 if ( $param === false ) {
899 $this->error( "\nERROR: $option parameter needs a value after it\n" );
900 $this->maybeHelp( true );
902 $this->setParam( $options, $option, $param );
904 $this->setParam( $options, $option, 1 );
912 $this->mOptions
= $options;
913 $this->mArgs
= $args;
914 $this->loadSpecialVars();
915 $this->mInputLoaded
= true;
919 * Helper function used solely by loadParamsAndArgs
920 * to prevent code duplication
922 * This sets the param in the options array based on
923 * whether or not it can be specified multiple times.
926 * @param array $options
927 * @param string $option
928 * @param mixed $value
930 private function setParam( &$options, $option, $value ) {
931 $this->orderedOptions
[] = [ $option, $value ];
933 if ( isset( $this->mParams
[$option] ) ) {
934 $multi = $this->mParams
[$option]['multiOccurrence'];
938 $exists = array_key_exists( $option, $options );
939 if ( $multi && $exists ) {
940 $options[$option][] = $value;
941 } elseif ( $multi ) {
942 $options[$option] = [ $value ];
943 } elseif ( !$exists ) {
944 $options[$option] = $value;
946 $this->error( "\nERROR: $option parameter given twice\n" );
947 $this->maybeHelp( true );
952 * Process command line arguments
953 * $mOptions becomes an array with keys set to the option names
954 * $mArgs becomes a zero-based array containing the non-option arguments
956 * @param string|null $self The name of the script, if any
957 * @param array|null $opts An array of options, in form of key=>value
958 * @param array|null $args An array of command line arguments
960 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
961 # If we were given opts or args, set those and return early
963 $this->mSelf
= $self;
964 $this->mInputLoaded
= true;
967 $this->mOptions
= $opts;
968 $this->mInputLoaded
= true;
971 $this->mArgs
= $args;
972 $this->mInputLoaded
= true;
975 # If we've already loaded input (either by user values or from $argv)
976 # skip on loading it again. The array_shift() will corrupt values if
977 # it's run again and again
978 if ( $this->mInputLoaded
) {
979 $this->loadSpecialVars();
985 $this->mSelf
= $argv[0];
986 $this->loadWithArgv( array_slice( $argv, 1 ) );
990 * Run some validation checks on the params, etc
992 public function validateParamsAndArgs() {
994 # Check to make sure we've got all the required options
995 foreach ( $this->mParams
as $opt => $info ) {
996 if ( $info['require'] && !$this->hasOption( $opt ) ) {
997 $this->error( "Param $opt required!" );
1001 # Check arg list too
1002 foreach ( $this->mArgList
as $k => $info ) {
1003 if ( $info['require'] && !$this->hasArg( $k ) ) {
1004 $this->error( 'Argument <' . $info['name'] . '> required!' );
1008 if ( !$this->mAllowUnregisteredOptions
) {
1009 # Check for unexpected options
1010 foreach ( $this->mOptions
as $opt => $val ) {
1011 if ( !$this->supportsOption( $opt ) ) {
1012 $this->error( "Unexpected option $opt!" );
1018 $this->maybeHelp( $die );
1022 * Handle the special variables that are global to all scripts
1024 protected function loadSpecialVars() {
1025 if ( $this->hasOption( 'dbuser' ) ) {
1026 $this->mDbUser
= $this->getOption( 'dbuser' );
1028 if ( $this->hasOption( 'dbpass' ) ) {
1029 $this->mDbPass
= $this->getOption( 'dbpass' );
1031 if ( $this->hasOption( 'quiet' ) ) {
1032 $this->mQuiet
= true;
1034 if ( $this->hasOption( 'batch-size' ) ) {
1035 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1040 * Maybe show the help.
1041 * @param bool $force Whether to force the help to show, default false
1043 protected function maybeHelp( $force = false ) {
1044 if ( !$force && !$this->hasOption( 'help' ) ) {
1048 $screenWidth = 80; // TODO: Calculate this!
1050 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1052 ksort( $this->mParams
);
1053 $this->mQuiet
= false;
1056 if ( $this->mDescription
) {
1057 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1059 $output = "\nUsage: php " . basename( $this->mSelf
);
1061 // ... append parameters ...
1062 if ( $this->mParams
) {
1063 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1066 // ... and append arguments.
1067 if ( $this->mArgList
) {
1069 foreach ( $this->mArgList
as $k => $arg ) {
1070 if ( $arg['require'] ) {
1071 $output .= '<' . $arg['name'] . '>';
1073 $output .= '[' . $arg['name'] . ']';
1075 if ( $k < count( $this->mArgList
) - 1 ) {
1080 $this->output( "$output\n\n" );
1082 # TODO abstract some repetitive code below
1084 // Generic parameters
1085 $this->output( "Generic maintenance parameters:\n" );
1086 foreach ( $this->mGenericParameters
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" );
1097 $scriptDependantParams = $this->mDependantParameters
;
1098 if ( count( $scriptDependantParams ) > 0 ) {
1099 $this->output( "Script dependant parameters:\n" );
1100 // Parameters description
1101 foreach ( $scriptDependantParams as $par => $info ) {
1102 if ( $info['shortName'] !== false ) {
1103 $par .= " (-{$info['shortName']})";
1106 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1107 "\n$tab$tab" ) . "\n"
1110 $this->output( "\n" );
1113 // Script specific parameters not defined on construction by
1114 // Maintenance::addDefaultParams()
1115 $scriptSpecificParams = array_diff_key(
1116 # all script parameters:
1118 # remove the Maintenance default parameters:
1119 $this->mGenericParameters
,
1120 $this->mDependantParameters
1122 if ( count( $scriptSpecificParams ) > 0 ) {
1123 $this->output( "Script specific parameters:\n" );
1124 // Parameters description
1125 foreach ( $scriptSpecificParams as $par => $info ) {
1126 if ( $info['shortName'] !== false ) {
1127 $par .= " (-{$info['shortName']})";
1130 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1131 "\n$tab$tab" ) . "\n"
1134 $this->output( "\n" );
1138 if ( count( $this->mArgList
) > 0 ) {
1139 $this->output( "Arguments:\n" );
1140 // Arguments description
1141 foreach ( $this->mArgList
as $info ) {
1142 $openChar = $info['require'] ?
'<' : '[';
1143 $closeChar = $info['require'] ?
'>' : ']';
1145 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1146 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1149 $this->output( "\n" );
1156 * Handle some last-minute setup here.
1158 public function finalSetup() {
1159 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1160 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1161 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1163 # Turn off output buffering again, it might have been turned on in the settings files
1164 if ( ob_get_level() ) {
1168 $wgCommandLineMode = true;
1170 # Override $wgServer
1171 if ( $this->hasOption( 'server' ) ) {
1172 $wgServer = $this->getOption( 'server', $wgServer );
1175 # If these were passed, use them
1176 if ( $this->mDbUser
) {
1177 $wgDBadminuser = $this->mDbUser
;
1179 if ( $this->mDbPass
) {
1180 $wgDBadminpassword = $this->mDbPass
;
1182 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1183 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1185 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1188 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1189 $wgDBuser = $wgDBadminuser;
1190 $wgDBpassword = $wgDBadminpassword;
1192 if ( $wgDBservers ) {
1194 * @var $wgDBservers array
1196 foreach ( $wgDBservers as $i => $server ) {
1197 $wgDBservers[$i]['user'] = $wgDBuser;
1198 $wgDBservers[$i]['password'] = $wgDBpassword;
1201 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1202 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1203 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1205 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1208 # Apply debug settings
1209 if ( $this->hasOption( 'mwdebug' ) ) {
1210 require __DIR__
. '/../includes/DevelopmentSettings.php';
1213 // Per-script profiling; useful for debugging
1214 $this->activateProfiler();
1216 $this->afterFinalSetup();
1218 $wgShowExceptionDetails = true;
1219 $wgShowHostnames = true;
1221 Wikimedia\
suppressWarnings();
1222 set_time_limit( 0 );
1223 Wikimedia\restoreWarnings
();
1225 $this->adjustMemoryLimit();
1229 * Execute a callback function at the end of initialisation
1231 protected function afterFinalSetup() {
1232 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1233 call_user_func( MW_CMDLINE_CALLBACK
);
1238 * Potentially debug globals. Originally a feature only
1241 public function globals() {
1242 if ( $this->hasOption( 'globals' ) ) {
1243 print_r( $GLOBALS );
1248 * Generic setup for most installs. Returns the location of LocalSettings
1251 public function loadSettings() {
1252 global $wgCommandLineMode, $IP;
1254 if ( isset( $this->mOptions
['conf'] ) ) {
1255 $settingsFile = $this->mOptions
['conf'];
1256 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1257 $settingsFile = MW_CONFIG_FILE
;
1259 $settingsFile = "$IP/LocalSettings.php";
1261 if ( isset( $this->mOptions
['wiki'] ) ) {
1262 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1263 define( 'MW_DB', $bits[0] );
1264 define( 'MW_PREFIX', $bits[1] ??
'' );
1265 } elseif ( isset( $this->mOptions
['server'] ) ) {
1266 // Provide the option for site admins to detect and configure
1267 // multiple wikis based on server names. This offers --server
1268 // as alternative to --wiki.
1269 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1270 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1273 if ( !is_readable( $settingsFile ) ) {
1274 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1275 "must exist and be readable in the source directory.\n" .
1276 "Use --conf to specify it." );
1278 $wgCommandLineMode = true;
1280 return $settingsFile;
1284 * Support function for cleaning up redundant text records
1285 * @param bool $delete Whether or not to actually delete the records
1286 * @author Rob Church <robchur@gmail.com>
1288 public function purgeRedundantText( $delete = true ) {
1289 global $wgMultiContentRevisionSchemaMigrationStage;
1291 # Data should come off the master, wrapped in a transaction
1292 $dbw = $this->getDB( DB_MASTER
);
1293 $this->beginTransaction( $dbw, __METHOD__
);
1295 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1296 # Get "active" text records from the revisions table
1298 $this->output( 'Searching for active text records in revisions table...' );
1299 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1300 foreach ( $res as $row ) {
1301 $cur[] = $row->rev_text_id
;
1303 $this->output( "done.\n" );
1305 # Get "active" text records from the archive table
1306 $this->output( 'Searching for active text records in archive table...' );
1307 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1308 foreach ( $res as $row ) {
1309 # old pre-MW 1.5 records can have null ar_text_id's.
1310 if ( $row->ar_text_id
!== null ) {
1311 $cur[] = $row->ar_text_id
;
1314 $this->output( "done.\n" );
1316 # Get "active" text records via the content table
1318 $this->output( 'Searching for active text records via contents table...' );
1319 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1320 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1321 foreach ( $res as $row ) {
1322 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1327 $this->output( "done.\n" );
1329 $this->output( "done.\n" );
1331 # Get the IDs of all text records not in these sets
1332 $this->output( 'Searching for inactive text records...' );
1333 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1334 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1336 foreach ( $res as $row ) {
1337 $old[] = $row->old_id
;
1339 $this->output( "done.\n" );
1341 # Inform the user of what we're going to do
1342 $count = count( $old );
1343 $this->output( "$count inactive items found.\n" );
1345 # Delete as appropriate
1346 if ( $delete && $count ) {
1347 $this->output( 'Deleting...' );
1348 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1349 $this->output( "done.\n" );
1352 $this->commitTransaction( $dbw, __METHOD__
);
1356 * Get the maintenance directory.
1359 protected function getDir() {
1364 * Returns a database to be used by current maintenance script. It can be set by setDB().
1365 * If not set, wfGetDB() will be used.
1366 * This function has the same parameters as wfGetDB()
1368 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1369 * @param string|string[] $groups default: empty array
1370 * @param string|bool $wiki default: current wiki
1371 * @return IMaintainableDatabase
1373 protected function getDB( $db, $groups = [], $wiki = false ) {
1374 if ( $this->mDb
=== null ) {
1375 return wfGetDB( $db, $groups, $wiki );
1381 * Sets database object to be returned by getDB().
1383 * @param IDatabase $db
1385 public function setDB( IDatabase
$db ) {
1390 * Begin a transcation on a DB
1392 * This method makes it clear that begin() is called from a maintenance script,
1393 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1395 * @param IDatabase $dbw
1396 * @param string $fname Caller name
1399 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1400 $dbw->begin( $fname );
1404 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1406 * This method makes it clear that commit() is called from a maintenance script,
1407 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1409 * @param IDatabase $dbw
1410 * @param string $fname Caller name
1411 * @return bool Whether the replica DB wait succeeded
1414 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1415 $dbw->commit( $fname );
1416 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1417 $waitSucceeded = $lbFactory->waitForReplication(
1418 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1420 $this->lastReplicationWait
= microtime( true );
1421 return $waitSucceeded;
1425 * Rollback the transcation on a DB handle
1427 * This method makes it clear that rollback() is called from a maintenance script,
1428 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1430 * @param IDatabase $dbw
1431 * @param string $fname Caller name
1434 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1435 $dbw->rollback( $fname );
1439 * Lock the search index
1440 * @param IMaintainableDatabase &$db
1442 private function lockSearchindex( $db ) {
1443 $write = [ 'searchindex' ];
1453 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1458 * @param IMaintainableDatabase &$db
1460 private function unlockSearchindex( $db ) {
1461 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1465 * Unlock and lock again
1466 * Since the lock is low-priority, queued reads will be able to complete
1467 * @param IMaintainableDatabase &$db
1469 private function relockSearchindex( $db ) {
1470 $this->unlockSearchindex( $db );
1471 $this->lockSearchindex( $db );
1475 * Perform a search index update with locking
1476 * @param int $maxLockTime The maximum time to keep the search index locked.
1477 * @param string $callback The function that will update the function.
1478 * @param IMaintainableDatabase $dbw
1479 * @param array $results
1481 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1485 if ( $maxLockTime ) {
1486 $this->output( " --- Waiting for lock ---" );
1487 $this->lockSearchindex( $dbw );
1489 $this->output( "\n" );
1492 # Loop through the results and do a search update
1493 foreach ( $results as $row ) {
1494 # Allow reads to be processed
1495 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1496 $this->output( " --- Relocking ---" );
1497 $this->relockSearchindex( $dbw );
1499 $this->output( "\n" );
1501 call_user_func( $callback, $dbw, $row );
1504 # Unlock searchindex
1505 if ( $maxLockTime ) {
1506 $this->output( " --- Unlocking --" );
1507 $this->unlockSearchindex( $dbw );
1508 $this->output( "\n" );
1513 * Update the searchindex table for a given pageid
1514 * @param IDatabase $dbw A database write handle
1515 * @param int $pageId The page ID to update.
1516 * @return null|string
1518 public function updateSearchIndexForPage( $dbw, $pageId ) {
1519 // Get current revision
1520 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1523 $titleObj = $rev->getTitle();
1524 $title = $titleObj->getPrefixedDBkey();
1525 $this->output( "$title..." );
1526 # Update searchindex
1527 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1529 $this->output( "\n" );
1536 * Count down from $seconds to zero on the terminal, with a one-second pause
1537 * between showing each number. If the maintenance script is in quiet mode,
1538 * this function does nothing.
1542 * @codeCoverageIgnore
1543 * @param int $seconds
1545 protected function countDown( $seconds ) {
1546 if ( $this->isQuiet() ) {
1549 for ( $i = $seconds; $i >= 0; $i-- ) {
1550 if ( $i != $seconds ) {
1551 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1553 $this->output( $i );
1558 $this->output( "\n" );
1562 * Wrapper for posix_isatty()
1563 * We default as considering stdin a tty (for nice readline methods)
1564 * but treating stout as not a tty to avoid color codes
1566 * @param mixed $fd File descriptor
1569 public static function posix_isatty( $fd ) {
1570 if ( !function_exists( 'posix_isatty' ) ) {
1573 return posix_isatty( $fd );
1578 * Prompt the console for input
1579 * @param string $prompt What to begin the line with, like '> '
1580 * @return string Response
1582 public static function readconsole( $prompt = '> ' ) {
1583 static $isatty = null;
1584 if ( is_null( $isatty ) ) {
1585 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1588 if ( $isatty && function_exists( 'readline' ) ) {
1589 return readline( $prompt );
1592 $st = self
::readlineEmulation( $prompt );
1594 if ( feof( STDIN
) ) {
1597 $st = fgets( STDIN
, 1024 );
1600 if ( $st === false ) {
1603 $resp = trim( $st );
1610 * Emulate readline()
1611 * @param string $prompt What to begin the line with, like '> '
1614 private static function readlineEmulation( $prompt ) {
1615 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1616 if ( !wfIsWindows() && $bash ) {
1618 $encPrompt = wfEscapeShellArg( $prompt );
1619 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1620 $encCommand = wfEscapeShellArg( $command );
1621 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1623 if ( $retval == 0 ) {
1625 } elseif ( $retval == 127 ) {
1626 // Couldn't execute bash even though we thought we saw it.
1627 // Shell probably spit out an error message, sorry :(
1628 // Fall through to fgets()...
1635 // Fallback... we'll have no editing controls, EWWW
1636 if ( feof( STDIN
) ) {
1641 return fgets( STDIN
, 1024 );
1645 * Get the terminal size as a two-element array where the first element
1646 * is the width (number of columns) and the second element is the height
1651 public static function getTermSize() {
1652 $default = [ 80, 50 ];
1653 if ( wfIsWindows() ) {
1656 if ( Shell
::isDisabled() ) {
1659 // It's possible to get the screen size with VT-100 terminal escapes,
1660 // but reading the responses is not possible without setting raw mode
1661 // (unless you want to require the user to press enter), and that
1662 // requires an ioctl(), which we can't do. So we have to shell out to
1663 // something that can do the relevant syscalls. There are a few
1664 // options. Linux and Mac OS X both have "stty size" which does the
1666 $result = Shell
::command( 'stty', 'size' )
1668 if ( $result->getExitCode() !== 0 ) {
1671 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1674 return [ intval( $m[2] ), intval( $m[1] ) ];
1678 * Call this to set up the autoloader to allow classes to be used from the
1681 public static function requireTestsAutoloader() {
1682 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1687 * Fake maintenance wrapper, mostly used for the web installer/updater
1689 class FakeMaintenance
extends Maintenance
{
1690 protected $mSelf = "FakeMaintenanceScript";
1692 public function execute() {
1697 * Class for scripts that perform database maintenance and want to log the
1698 * update in `updatelog` so we can later skip it
1700 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1701 public function __construct() {
1702 parent
::__construct();
1703 $this->addOption( 'force', 'Run the update even if it was completed already' );
1704 $this->setBatchSize( 200 );
1707 public function execute() {
1708 $db = $this->getDB( DB_MASTER
);
1709 $key = $this->getUpdateKey();
1711 if ( !$this->hasOption( 'force' )
1712 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1714 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1719 if ( !$this->doDBUpdates() ) {
1723 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' );
1729 * Message to show that the update was done already and was just skipped
1732 protected function updateSkippedMessage() {
1733 $key = $this->getUpdateKey();
1735 return "Update '{$key}' already logged 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();