3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Bail on old versions of PHP, or if composer has not been run yet to install
25 require_once __DIR__
. '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'cli' );
28 use MediaWiki\Shell\Shell
;
29 use Wikimedia\Rdbms\DBReplicationWaitError
;
32 * @defgroup MaintenanceArchive Maintenance archives
33 * @ingroup Maintenance
36 // Define this so scripts can easily find doMaintenance.php
37 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
40 * @deprecated since 1.31
42 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
46 use Wikimedia\Rdbms\IDatabase
;
47 use MediaWiki\Logger\LoggerFactory
;
48 use MediaWiki\MediaWikiServices
;
49 use Wikimedia\Rdbms\LBFactory
;
50 use Wikimedia\Rdbms\IMaintainableDatabase
;
53 * Abstract maintenance class for quickly writing and churning out
54 * maintenance scripts with minimal effort. All that _must_ be defined
55 * is the execute() method. See docs/maintenance.txt for more info
56 * and a quick demo of how to use it.
59 * @ingroup Maintenance
61 abstract class Maintenance
{
63 * Constants for DB access type
64 * @see Maintenance::getDbType()
70 // Const for getStdin()
71 const STDIN_ALL
= 'all';
73 // This is the desired params
74 protected $mParams = [];
76 // Array of mapping short parameters to long ones
77 protected $mShortParamsMap = [];
79 // Array of desired args
80 protected $mArgList = [];
82 // This is the list of options that were actually passed
83 protected $mOptions = [];
85 // This is the list of arguments that were actually passed
86 protected $mArgs = [];
88 // Name of the script currently running
91 // Special vars for params that are always used
92 protected $mQuiet = false;
93 protected $mDbUser, $mDbPass;
95 // A description of the script, children should change this via addDescription()
96 protected $mDescription = '';
98 // Have we already loaded our user input?
99 protected $mInputLoaded = false;
102 * Batch size. If a script supports this, they should set
103 * a default with setBatchSize()
107 protected $mBatchSize = null;
109 // Generic options added by addDefaultParams()
110 private $mGenericParameters = [];
111 // Generic options which might or not be supported by the script
112 private $mDependantParameters = [];
115 * Used by getDB() / setDB()
116 * @var IMaintainableDatabase
120 /** @var float UNIX timestamp */
121 private $lastReplicationWait = 0.0;
124 * Used when creating separate schema files.
130 * Accessible via getConfig()
137 * @see Maintenance::requireExtension
140 private $requiredExtensions = [];
143 * Used to read the options in the order they were passed.
144 * Useful for option chaining (Ex. dumpBackup.php). It will
145 * be an empty array if the options are passed in through
146 * loadParamsAndArgs( $self, $opts, $args ).
148 * This is an array of arrays where
149 * 0 => the option and 1 => parameter value.
153 public $orderedOptions = [];
156 * Default constructor. Children should call this *first* if implementing
157 * their own constructors
159 public function __construct() {
160 // Setup $IP, using MW_INSTALL_PATH if it exists
162 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
163 ?
getenv( 'MW_INSTALL_PATH' )
164 : realpath( __DIR__
. '/..' );
166 $this->addDefaultParams();
167 register_shutdown_function( [ $this, 'outputChanneled' ], false );
171 * Should we execute the maintenance script, or just allow it to be included
172 * as a standalone class? It checks that the call stack only includes this
173 * function and "requires" (meaning was called from the file scope)
177 public static function shouldExecute() {
178 global $wgCommandLineMode;
180 if ( !function_exists( 'debug_backtrace' ) ) {
181 // If someone has a better idea...
182 return $wgCommandLineMode;
185 $bt = debug_backtrace();
186 $count = count( $bt );
188 return false; // sanity
190 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
191 return false; // last call should be to this function
193 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
194 for ( $i = 1; $i < $count; $i++
) {
195 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
196 return false; // previous calls should all be "requires"
204 * Do the actual work. All child classes will need to implement this
206 * @return bool|null|void True for success, false for failure. Not returning
207 * a value, or returning null, is also interpreted as success. Returning
208 * false for failure will cause doMaintenance.php to exit the process
209 * with a non-zero exit status.
211 abstract public function execute();
214 * Add a parameter to the script. Will be displayed on --help
215 * with the associated description
217 * @param string $name The name of the param (help, version, etc)
218 * @param string $description The description of the param to show on --help
219 * @param bool $required Is the param required?
220 * @param bool $withArg Is an argument required with this option?
221 * @param string|bool $shortName Character to use as short name
222 * @param bool $multiOccurrence Can this option be passed multiple times?
224 protected function addOption( $name, $description, $required = false,
225 $withArg = false, $shortName = false, $multiOccurrence = false
227 $this->mParams
[$name] = [
228 'desc' => $description,
229 'require' => $required,
230 'withArg' => $withArg,
231 'shortName' => $shortName,
232 'multiOccurrence' => $multiOccurrence
235 if ( $shortName !== false ) {
236 $this->mShortParamsMap
[$shortName] = $name;
241 * Checks to see if a particular param exists.
242 * @param string $name The name of the param
245 protected function hasOption( $name ) {
246 return isset( $this->mOptions
[$name] );
250 * Get an option, or return the default.
252 * If the option was added to support multiple occurrences,
253 * this will return an array.
255 * @param string $name The name of the param
256 * @param mixed $default Anything you want, default null
259 protected function getOption( $name, $default = null ) {
260 if ( $this->hasOption( $name ) ) {
261 return $this->mOptions
[$name];
263 // Set it so we don't have to provide the default again
264 $this->mOptions
[$name] = $default;
266 return $this->mOptions
[$name];
271 * Add some args that are needed
272 * @param string $arg Name of the arg, like 'start'
273 * @param string $description Short description of the arg
274 * @param bool $required Is this required?
276 protected function addArg( $arg, $description, $required = true ) {
277 $this->mArgList
[] = [
279 'desc' => $description,
280 'require' => $required
285 * Remove an option. Useful for removing options that won't be used in your script.
286 * @param string $name The option to remove.
288 protected function deleteOption( $name ) {
289 unset( $this->mParams
[$name] );
293 * Set the description text.
294 * @param string $text The text of the description
296 protected function addDescription( $text ) {
297 $this->mDescription
= $text;
301 * Does a given argument exist?
302 * @param int $argId The integer value (from zero) for the arg
305 protected function hasArg( $argId = 0 ) {
306 return isset( $this->mArgs
[$argId] );
311 * @param int $argId The integer value (from zero) for the arg
312 * @param mixed $default The default if it doesn't exist
315 protected function getArg( $argId = 0, $default = null ) {
316 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
326 protected function getBatchSize() {
327 return $this->mBatchSize
;
331 * Set the batch size.
332 * @param int $s The number of operations to do in a batch
334 protected function setBatchSize( $s = 0 ) {
335 $this->mBatchSize
= $s;
337 // If we support $mBatchSize, show the option.
338 // Used to be in addDefaultParams, but in order for that to
339 // work, subclasses would have to call this function in the constructor
340 // before they called parent::__construct which is just weird
341 // (and really wasn't done).
342 if ( $this->mBatchSize
) {
343 $this->addOption( 'batch-size', 'Run this many operations ' .
344 'per batch, default: ' . $this->mBatchSize
, false, true );
345 if ( isset( $this->mParams
['batch-size'] ) ) {
346 // This seems a little ugly...
347 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
353 * Get the script's name
356 public function getName() {
361 * Return input from stdin.
362 * @param int $len The number of bytes to read. If null, just return the handle.
363 * Maintenance::STDIN_ALL returns the full length
366 protected function getStdin( $len = null ) {
367 if ( $len == self
::STDIN_ALL
) {
368 return file_get_contents( 'php://stdin' );
370 $f = fopen( 'php://stdin', 'rt' );
374 $input = fgets( $f, $len );
377 return rtrim( $input );
383 public function isQuiet() {
384 return $this->mQuiet
;
388 * Throw some output to the user. Scripts can call this with no fears,
389 * as we handle all --quiet stuff here
390 * @param string $out The text to show to the user
391 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
393 protected function output( $out, $channel = null ) {
394 // This is sometimes called very early, before Setup.php is included.
395 if ( class_exists( MediaWikiServices
::class ) ) {
396 // Try to periodically flush buffered metrics to avoid OOMs
397 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
398 if ( $stats->getDataCount() > 1000 ) {
399 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
403 if ( $this->mQuiet
) {
406 if ( $channel === null ) {
407 $this->cleanupChanneled();
410 $out = preg_replace( '/\n\z/', '', $out );
411 $this->outputChanneled( $out, $channel );
416 * Throw an error to the user. Doesn't respect --quiet, so don't use
417 * this for non-error output
418 * @param string $err The error to display
419 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
421 protected function error( $err, $die = 0 ) {
422 if ( intval( $die ) !== 0 ) {
423 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
424 $this->fatalError( $err, intval( $die ) );
426 $this->outputChanneled( false );
428 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
429 !defined( 'MW_PHPUNIT_TEST' )
431 fwrite( STDERR
, $err . "\n" );
438 * Output a message and terminate the current script.
440 * @param string $msg Error message
441 * @param int $exitCode PHP exit status. Should be in range 1-254.
444 protected function fatalError( $msg, $exitCode = 1 ) {
445 $this->error( $msg );
449 private $atLineStart = true;
450 private $lastChannel = null;
453 * Clean up channeled output. Output a newline if necessary.
455 public function cleanupChanneled() {
456 if ( !$this->atLineStart
) {
458 $this->atLineStart
= true;
463 * Message outputter with channeled message support. Messages on the
464 * same channel are concatenated, but any intervening messages in another
465 * channel start a new line.
466 * @param string $msg The message without trailing newline
467 * @param string $channel Channel identifier or null for no
468 * channel. Channel comparison uses ===.
470 public function outputChanneled( $msg, $channel = null ) {
471 if ( $msg === false ) {
472 $this->cleanupChanneled();
477 // End the current line if necessary
478 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
484 $this->atLineStart
= false;
485 if ( $channel === null ) {
486 // For unchanneled messages, output trailing newline immediately
488 $this->atLineStart
= true;
490 $this->lastChannel
= $channel;
494 * Does the script need different DB access? By default, we give Maintenance
495 * scripts normal rights to the DB. Sometimes, a script needs admin rights
496 * access for a reason and sometimes they want no access. Subclasses should
497 * override and return one of the following values, as needed:
498 * Maintenance::DB_NONE - For no DB access at all
499 * Maintenance::DB_STD - For normal DB access, default
500 * Maintenance::DB_ADMIN - For admin DB access
503 public function getDbType() {
508 * Add the default parameters to the scripts
510 protected function addDefaultParams() {
511 # Generic (non script dependant) options:
513 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
514 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
515 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
516 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
517 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
520 'Set a specific memory limit for the script, '
521 . '"max" for no limit or "default" to avoid changing it',
525 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
526 "http://en.wikipedia.org. This is sometimes necessary because " .
527 "server name detection may fail in command line scripts.", false, true );
528 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
529 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
530 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
532 # Save generic options to display them separately in help
533 $this->mGenericParameters
= $this->mParams
;
535 # Script dependant options:
537 // If we support a DB, show the options
538 if ( $this->getDbType() > 0 ) {
539 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
540 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
541 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
544 # Save additional script dependant options to display
545 # Â them separately in help
546 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
553 public function getConfig() {
554 if ( $this->config
=== null ) {
555 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
558 return $this->config
;
563 * @param Config $config
565 public function setConfig( Config
$config ) {
566 $this->config
= $config;
570 * Indicate that the specified extension must be
571 * loaded before the script can run.
573 * This *must* be called in the constructor.
576 * @param string $name
578 protected function requireExtension( $name ) {
579 $this->requiredExtensions
[] = $name;
583 * Verify that the required extensions are installed
587 public function checkRequiredExtensions() {
588 $registry = ExtensionRegistry
::getInstance();
590 foreach ( $this->requiredExtensions
as $name ) {
591 if ( !$registry->isLoaded( $name ) ) {
597 $joined = implode( ', ', $missing );
598 $msg = "The following extensions are required to be installed "
599 . "for this script to run: $joined. Please enable them and then try again.";
600 $this->fatalError( $msg );
605 * Set triggers like when to try to run deferred updates
608 public function setAgentAndTriggers() {
609 if ( function_exists( 'posix_getpwuid' ) ) {
610 $agent = posix_getpwuid( posix_geteuid() )['name'];
614 $agent .= '@' . wfHostname();
616 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
617 // Add a comment for easy SHOW PROCESSLIST interpretation
618 $lbFactory->setAgentName(
619 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
621 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
625 * @param LBFactory $LBFactory
626 * @param Config $config
629 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
630 $services = MediaWikiServices
::getInstance();
631 $stats = $services->getStatsdDataFactory();
632 // Hook into period lag checks which often happen in long-running scripts
633 $lbFactory = $services->getDBLoadBalancerFactory();
634 $lbFactory->setWaitForReplicationListener(
636 function () use ( $stats, $config ) {
637 // Check config in case of JobRunner and unit tests
638 if ( $config->get( 'CommandLineMode' ) ) {
639 DeferredUpdates
::tryOpportunisticExecute( 'run' );
641 // Try to periodically flush buffered metrics to avoid OOMs
642 MediaWiki
::emitBufferedStatsdData( $stats, $config );
645 // Check for other windows to run them. A script may read or do a few writes
646 // to the master but mostly be writing to something else, like a file store.
647 $lbFactory->getMainLB()->setTransactionListener(
649 function ( $trigger ) use ( $stats, $config ) {
650 // Check config in case of JobRunner and unit tests
651 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
652 DeferredUpdates
::tryOpportunisticExecute( 'run' );
654 // Try to periodically flush buffered metrics to avoid OOMs
655 MediaWiki
::emitBufferedStatsdData( $stats, $config );
661 * Run a child maintenance script. Pass all of the current arguments
663 * @param string $maintClass A name of a child maintenance class
664 * @param string $classFile Full path of where the child is
665 * @return Maintenance
667 public function runChild( $maintClass, $classFile = null ) {
668 // Make sure the class is loaded first
669 if ( !class_exists( $maintClass ) ) {
671 require_once $classFile;
673 if ( !class_exists( $maintClass ) ) {
674 $this->error( "Cannot spawn child: $maintClass" );
679 * @var $child Maintenance
681 $child = new $maintClass();
682 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
683 if ( !is_null( $this->mDb
) ) {
684 $child->setDB( $this->mDb
);
691 * Do some sanity checking and basic setup
693 public function setup() {
694 global $IP, $wgCommandLineMode;
696 # Abort if called from a web server
697 # wfIsCLI() is not available yet
698 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
699 $this->fatalError( 'This script must be run from the command line' );
702 if ( $IP === null ) {
703 $this->fatalError( "\$IP not set, aborting!\n" .
704 '(Did you forget to call parent::__construct() in your maintenance script?)' );
707 # Make sure we can handle script parameters
708 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
709 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
712 // Send PHP warnings and errors to stderr instead of stdout.
713 // This aids in diagnosing problems, while keeping messages
714 // out of redirected output.
715 if ( ini_get( 'display_errors' ) ) {
716 ini_set( 'display_errors', 'stderr' );
719 $this->loadParamsAndArgs();
722 # Set the memory limit
723 # Note we need to set it again later in cache LocalSettings changed it
724 $this->adjustMemoryLimit();
726 # Set max execution time to 0 (no limit). PHP.net says that
727 # "When running PHP from the command line the default setting is 0."
728 # But sometimes this doesn't seem to be the case.
729 ini_set( 'max_execution_time', 0 );
731 # Define us as being in MediaWiki
732 define( 'MEDIAWIKI', true );
734 $wgCommandLineMode = true;
736 # Turn off output buffering if it's on
737 while ( ob_get_level() > 0 ) {
741 $this->validateParamsAndArgs();
745 * Normally we disable the memory_limit when running admin scripts.
746 * Some scripts may wish to actually set a limit, however, to avoid
747 * blowing up unexpectedly. We also support a --memory-limit option,
748 * to allow sysadmins to explicitly set one if they'd prefer to override
749 * defaults (or for people using Suhosin which yells at you for trying
750 * to disable the limits)
753 public function memoryLimit() {
754 $limit = $this->getOption( 'memory-limit', 'max' );
755 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
760 * Adjusts PHP's memory limit to better suit our needs, if needed.
762 protected function adjustMemoryLimit() {
763 $limit = $this->memoryLimit();
764 if ( $limit == 'max' ) {
765 $limit = -1; // no memory limit
767 if ( $limit != 'default' ) {
768 ini_set( 'memory_limit', $limit );
773 * Activate the profiler (assuming $wgProfiler is set)
775 protected function activateProfiler() {
776 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
778 $output = $this->getOption( 'profiler' );
783 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
784 $class = $wgProfiler['class'];
785 /** @var Profiler $profiler */
786 $profiler = new $class(
787 [ 'sampling' => 1, 'output' => [ $output ] ]
789 +
[ 'threshold' => $wgProfileLimit ]
791 $profiler->setTemplated( true );
792 Profiler
::replaceStubInstance( $profiler );
795 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
796 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
797 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
801 * Clear all params and arguments.
803 public function clearParamsAndArgs() {
804 $this->mOptions
= [];
806 $this->mInputLoaded
= false;
810 * Load params and arguments from a given array
811 * of command-line arguments
816 public function loadWithArgv( $argv ) {
819 $this->orderedOptions
= [];
822 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
823 if ( $arg == '--' ) {
824 # End of options, remainder should be considered arguments
825 $arg = next( $argv );
826 while ( $arg !== false ) {
828 $arg = next( $argv );
831 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
833 $option = substr( $arg, 2 );
834 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
835 $param = next( $argv );
836 if ( $param === false ) {
837 $this->error( "\nERROR: $option parameter needs a value after it\n" );
838 $this->maybeHelp( true );
841 $this->setParam( $options, $option, $param );
843 $bits = explode( '=', $option, 2 );
844 if ( count( $bits ) > 1 ) {
851 $this->setParam( $options, $option, $param );
853 } elseif ( $arg == '-' ) {
854 # Lonely "-", often used to indicate stdin or stdout.
856 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
858 $argLength = strlen( $arg );
859 for ( $p = 1; $p < $argLength; $p++
) {
861 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
862 $option = $this->mShortParamsMap
[$option];
865 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
866 $param = next( $argv );
867 if ( $param === false ) {
868 $this->error( "\nERROR: $option parameter needs a value after it\n" );
869 $this->maybeHelp( true );
871 $this->setParam( $options, $option, $param );
873 $this->setParam( $options, $option, 1 );
881 $this->mOptions
= $options;
882 $this->mArgs
= $args;
883 $this->loadSpecialVars();
884 $this->mInputLoaded
= true;
888 * Helper function used solely by loadParamsAndArgs
889 * to prevent code duplication
891 * This sets the param in the options array based on
892 * whether or not it can be specified multiple times.
895 * @param array $options
896 * @param string $option
897 * @param mixed $value
899 private function setParam( &$options, $option, $value ) {
900 $this->orderedOptions
[] = [ $option, $value ];
902 if ( isset( $this->mParams
[$option] ) ) {
903 $multi = $this->mParams
[$option]['multiOccurrence'];
907 $exists = array_key_exists( $option, $options );
908 if ( $multi && $exists ) {
909 $options[$option][] = $value;
910 } elseif ( $multi ) {
911 $options[$option] = [ $value ];
912 } elseif ( !$exists ) {
913 $options[$option] = $value;
915 $this->error( "\nERROR: $option parameter given twice\n" );
916 $this->maybeHelp( true );
921 * Process command line arguments
922 * $mOptions becomes an array with keys set to the option names
923 * $mArgs becomes a zero-based array containing the non-option arguments
925 * @param string $self The name of the script, if any
926 * @param array $opts An array of options, in form of key=>value
927 * @param array $args An array of command line arguments
929 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
930 # If we were given opts or args, set those and return early
932 $this->mSelf
= $self;
933 $this->mInputLoaded
= true;
936 $this->mOptions
= $opts;
937 $this->mInputLoaded
= true;
940 $this->mArgs
= $args;
941 $this->mInputLoaded
= true;
944 # If we've already loaded input (either by user values or from $argv)
945 # skip on loading it again. The array_shift() will corrupt values if
946 # it's run again and again
947 if ( $this->mInputLoaded
) {
948 $this->loadSpecialVars();
954 $this->mSelf
= $argv[0];
955 $this->loadWithArgv( array_slice( $argv, 1 ) );
959 * Run some validation checks on the params, etc
961 protected function validateParamsAndArgs() {
963 # Check to make sure we've got all the required options
964 foreach ( $this->mParams
as $opt => $info ) {
965 if ( $info['require'] && !$this->hasOption( $opt ) ) {
966 $this->error( "Param $opt required!" );
971 foreach ( $this->mArgList
as $k => $info ) {
972 if ( $info['require'] && !$this->hasArg( $k ) ) {
973 $this->error( 'Argument <' . $info['name'] . '> required!' );
979 $this->maybeHelp( true );
984 * Handle the special variables that are global to all scripts
986 protected function loadSpecialVars() {
987 if ( $this->hasOption( 'dbuser' ) ) {
988 $this->mDbUser
= $this->getOption( 'dbuser' );
990 if ( $this->hasOption( 'dbpass' ) ) {
991 $this->mDbPass
= $this->getOption( 'dbpass' );
993 if ( $this->hasOption( 'quiet' ) ) {
994 $this->mQuiet
= true;
996 if ( $this->hasOption( 'batch-size' ) ) {
997 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1002 * Maybe show the help.
1003 * @param bool $force Whether to force the help to show, default false
1005 protected function maybeHelp( $force = false ) {
1006 if ( !$force && !$this->hasOption( 'help' ) ) {
1010 $screenWidth = 80; // TODO: Calculate this!
1012 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1014 ksort( $this->mParams
);
1015 $this->mQuiet
= false;
1018 if ( $this->mDescription
) {
1019 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1021 $output = "\nUsage: php " . basename( $this->mSelf
);
1023 // ... append parameters ...
1024 if ( $this->mParams
) {
1025 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1028 // ... and append arguments.
1029 if ( $this->mArgList
) {
1031 foreach ( $this->mArgList
as $k => $arg ) {
1032 if ( $arg['require'] ) {
1033 $output .= '<' . $arg['name'] . '>';
1035 $output .= '[' . $arg['name'] . ']';
1037 if ( $k < count( $this->mArgList
) - 1 ) {
1042 $this->output( "$output\n\n" );
1044 # TODO abstract some repetitive code below
1046 // Generic parameters
1047 $this->output( "Generic maintenance parameters:\n" );
1048 foreach ( $this->mGenericParameters
as $par => $info ) {
1049 if ( $info['shortName'] !== false ) {
1050 $par .= " (-{$info['shortName']})";
1053 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1054 "\n$tab$tab" ) . "\n"
1057 $this->output( "\n" );
1059 $scriptDependantParams = $this->mDependantParameters
;
1060 if ( count( $scriptDependantParams ) > 0 ) {
1061 $this->output( "Script dependant parameters:\n" );
1062 // Parameters description
1063 foreach ( $scriptDependantParams as $par => $info ) {
1064 if ( $info['shortName'] !== false ) {
1065 $par .= " (-{$info['shortName']})";
1068 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1069 "\n$tab$tab" ) . "\n"
1072 $this->output( "\n" );
1075 // Script specific parameters not defined on construction by
1076 // Maintenance::addDefaultParams()
1077 $scriptSpecificParams = array_diff_key(
1078 # all script parameters:
1080 # remove the Maintenance default parameters:
1081 $this->mGenericParameters
,
1082 $this->mDependantParameters
1084 if ( count( $scriptSpecificParams ) > 0 ) {
1085 $this->output( "Script specific parameters:\n" );
1086 // Parameters description
1087 foreach ( $scriptSpecificParams as $par => $info ) {
1088 if ( $info['shortName'] !== false ) {
1089 $par .= " (-{$info['shortName']})";
1092 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1093 "\n$tab$tab" ) . "\n"
1096 $this->output( "\n" );
1100 if ( count( $this->mArgList
) > 0 ) {
1101 $this->output( "Arguments:\n" );
1102 // Arguments description
1103 foreach ( $this->mArgList
as $info ) {
1104 $openChar = $info['require'] ?
'<' : '[';
1105 $closeChar = $info['require'] ?
'>' : ']';
1107 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1108 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1111 $this->output( "\n" );
1118 * Handle some last-minute setup here.
1120 public function finalSetup() {
1121 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1122 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1123 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1125 # Turn off output buffering again, it might have been turned on in the settings files
1126 if ( ob_get_level() ) {
1130 $wgCommandLineMode = true;
1132 # Override $wgServer
1133 if ( $this->hasOption( 'server' ) ) {
1134 $wgServer = $this->getOption( 'server', $wgServer );
1137 # If these were passed, use them
1138 if ( $this->mDbUser
) {
1139 $wgDBadminuser = $this->mDbUser
;
1141 if ( $this->mDbPass
) {
1142 $wgDBadminpassword = $this->mDbPass
;
1144 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1145 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1147 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1150 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1151 $wgDBuser = $wgDBadminuser;
1152 $wgDBpassword = $wgDBadminpassword;
1154 if ( $wgDBservers ) {
1156 * @var $wgDBservers array
1158 foreach ( $wgDBservers as $i => $server ) {
1159 $wgDBservers[$i]['user'] = $wgDBuser;
1160 $wgDBservers[$i]['password'] = $wgDBpassword;
1163 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1164 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1165 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1167 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1170 # Apply debug settings
1171 if ( $this->hasOption( 'mwdebug' ) ) {
1172 require __DIR__
. '/../includes/DevelopmentSettings.php';
1175 // Per-script profiling; useful for debugging
1176 $this->activateProfiler();
1178 $this->afterFinalSetup();
1180 $wgShowSQLErrors = true;
1182 Wikimedia\
suppressWarnings();
1183 set_time_limit( 0 );
1184 Wikimedia\restoreWarnings
();
1186 $this->adjustMemoryLimit();
1190 * Execute a callback function at the end of initialisation
1192 protected function afterFinalSetup() {
1193 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1194 call_user_func( MW_CMDLINE_CALLBACK
);
1199 * Potentially debug globals. Originally a feature only
1202 public function globals() {
1203 if ( $this->hasOption( 'globals' ) ) {
1204 print_r( $GLOBALS );
1209 * Generic setup for most installs. Returns the location of LocalSettings
1212 public function loadSettings() {
1213 global $wgCommandLineMode, $IP;
1215 if ( isset( $this->mOptions
['conf'] ) ) {
1216 $settingsFile = $this->mOptions
['conf'];
1217 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1218 $settingsFile = MW_CONFIG_FILE
;
1220 $settingsFile = "$IP/LocalSettings.php";
1222 if ( isset( $this->mOptions
['wiki'] ) ) {
1223 $bits = explode( '-', $this->mOptions
['wiki'] );
1224 if ( count( $bits ) == 1 ) {
1227 define( 'MW_DB', $bits[0] );
1228 define( 'MW_PREFIX', $bits[1] );
1229 } elseif ( isset( $this->mOptions
['server'] ) ) {
1230 // Provide the option for site admins to detect and configure
1231 // multiple wikis based on server names. This offers --server
1232 // as alternative to --wiki.
1233 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1234 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1237 if ( !is_readable( $settingsFile ) ) {
1238 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1239 "must exist and be readable in the source directory.\n" .
1240 "Use --conf to specify it." );
1242 $wgCommandLineMode = true;
1244 return $settingsFile;
1248 * Support function for cleaning up redundant text records
1249 * @param bool $delete Whether or not to actually delete the records
1250 * @author Rob Church <robchur@gmail.com>
1252 public function purgeRedundantText( $delete = true ) {
1253 # Data should come off the master, wrapped in a transaction
1254 $dbw = $this->getDB( DB_MASTER
);
1255 $this->beginTransaction( $dbw, __METHOD__
);
1257 # Get "active" text records from the revisions table
1259 $this->output( 'Searching for active text records in revisions table...' );
1260 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1261 foreach ( $res as $row ) {
1262 $cur[] = $row->rev_text_id
;
1264 $this->output( "done.\n" );
1266 # Get "active" text records from the archive table
1267 $this->output( 'Searching for active text records in archive table...' );
1268 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1269 foreach ( $res as $row ) {
1270 # old pre-MW 1.5 records can have null ar_text_id's.
1271 if ( $row->ar_text_id
!== null ) {
1272 $cur[] = $row->ar_text_id
;
1275 $this->output( "done.\n" );
1277 # Get the IDs of all text records not in these sets
1278 $this->output( 'Searching for inactive text records...' );
1279 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1280 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1282 foreach ( $res as $row ) {
1283 $old[] = $row->old_id
;
1285 $this->output( "done.\n" );
1287 # Inform the user of what we're going to do
1288 $count = count( $old );
1289 $this->output( "$count inactive items found.\n" );
1291 # Delete as appropriate
1292 if ( $delete && $count ) {
1293 $this->output( 'Deleting...' );
1294 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1295 $this->output( "done.\n" );
1299 $this->commitTransaction( $dbw, __METHOD__
);
1303 * Get the maintenance directory.
1306 protected function getDir() {
1311 * Returns a database to be used by current maintenance script. It can be set by setDB().
1312 * If not set, wfGetDB() will be used.
1313 * This function has the same parameters as wfGetDB()
1315 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1316 * @param string|string[] $groups default: empty array
1317 * @param string|bool $wiki default: current wiki
1318 * @return IMaintainableDatabase
1320 protected function getDB( $db, $groups = [], $wiki = false ) {
1321 if ( is_null( $this->mDb
) ) {
1322 return wfGetDB( $db, $groups, $wiki );
1329 * Sets database object to be returned by getDB().
1331 * @param IDatabase $db
1333 public function setDB( IDatabase
$db ) {
1338 * Begin a transcation on a DB
1340 * This method makes it clear that begin() is called from a maintenance script,
1341 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1343 * @param IDatabase $dbw
1344 * @param string $fname Caller name
1347 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1348 $dbw->begin( $fname );
1352 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1354 * This method makes it clear that commit() is called from a maintenance script,
1355 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1357 * @param IDatabase $dbw
1358 * @param string $fname Caller name
1359 * @return bool Whether the replica DB wait succeeded
1362 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1363 $dbw->commit( $fname );
1365 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1366 $lbFactory->waitForReplication(
1367 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1369 $this->lastReplicationWait
= microtime( true );
1372 } catch ( DBReplicationWaitError
$e ) {
1378 * Rollback the transcation on a DB handle
1380 * This method makes it clear that rollback() is called from a maintenance script,
1381 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1383 * @param IDatabase $dbw
1384 * @param string $fname Caller name
1387 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1388 $dbw->rollback( $fname );
1392 * Lock the search index
1393 * @param IMaintainableDatabase &$db
1395 private function lockSearchindex( $db ) {
1396 $write = [ 'searchindex' ];
1406 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1411 * @param IMaintainableDatabase &$db
1413 private function unlockSearchindex( $db ) {
1414 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1418 * Unlock and lock again
1419 * Since the lock is low-priority, queued reads will be able to complete
1420 * @param IMaintainableDatabase &$db
1422 private function relockSearchindex( $db ) {
1423 $this->unlockSearchindex( $db );
1424 $this->lockSearchindex( $db );
1428 * Perform a search index update with locking
1429 * @param int $maxLockTime The maximum time to keep the search index locked.
1430 * @param string $callback The function that will update the function.
1431 * @param IMaintainableDatabase $dbw
1432 * @param array $results
1434 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1438 if ( $maxLockTime ) {
1439 $this->output( " --- Waiting for lock ---" );
1440 $this->lockSearchindex( $dbw );
1442 $this->output( "\n" );
1445 # Loop through the results and do a search update
1446 foreach ( $results as $row ) {
1447 # Allow reads to be processed
1448 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1449 $this->output( " --- Relocking ---" );
1450 $this->relockSearchindex( $dbw );
1452 $this->output( "\n" );
1454 call_user_func( $callback, $dbw, $row );
1457 # Unlock searchindex
1458 if ( $maxLockTime ) {
1459 $this->output( " --- Unlocking --" );
1460 $this->unlockSearchindex( $dbw );
1461 $this->output( "\n" );
1466 * Update the searchindex table for a given pageid
1467 * @param IDatabase $dbw A database write handle
1468 * @param int $pageId The page ID to update.
1469 * @return null|string
1471 public function updateSearchIndexForPage( $dbw, $pageId ) {
1472 // Get current revision
1473 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1476 $titleObj = $rev->getTitle();
1477 $title = $titleObj->getPrefixedDBkey();
1478 $this->output( "$title..." );
1479 # Update searchindex
1480 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1482 $this->output( "\n" );
1489 * Count down from $seconds to zero on the terminal, with a one-second pause
1490 * between showing each number. If the maintenance script is in quiet mode,
1491 * this function does nothing.
1495 * @codeCoverageIgnore
1496 * @param int $seconds
1498 protected function countDown( $seconds ) {
1499 if ( $this->isQuiet() ) {
1502 for ( $i = $seconds; $i >= 0; $i-- ) {
1503 if ( $i != $seconds ) {
1504 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1506 $this->output( $i );
1511 $this->output( "\n" );
1515 * Wrapper for posix_isatty()
1516 * We default as considering stdin a tty (for nice readline methods)
1517 * but treating stout as not a tty to avoid color codes
1519 * @param mixed $fd File descriptor
1522 public static function posix_isatty( $fd ) {
1523 if ( !function_exists( 'posix_isatty' ) ) {
1526 return posix_isatty( $fd );
1531 * Prompt the console for input
1532 * @param string $prompt What to begin the line with, like '> '
1533 * @return string Response
1535 public static function readconsole( $prompt = '> ' ) {
1536 static $isatty = null;
1537 if ( is_null( $isatty ) ) {
1538 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1541 if ( $isatty && function_exists( 'readline' ) ) {
1542 return readline( $prompt );
1545 $st = self
::readlineEmulation( $prompt );
1547 if ( feof( STDIN
) ) {
1550 $st = fgets( STDIN
, 1024 );
1553 if ( $st === false ) {
1556 $resp = trim( $st );
1563 * Emulate readline()
1564 * @param string $prompt What to begin the line with, like '> '
1567 private static function readlineEmulation( $prompt ) {
1568 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1569 if ( !wfIsWindows() && $bash ) {
1571 $encPrompt = wfEscapeShellArg( $prompt );
1572 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1573 $encCommand = wfEscapeShellArg( $command );
1574 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1576 if ( $retval == 0 ) {
1578 } elseif ( $retval == 127 ) {
1579 // Couldn't execute bash even though we thought we saw it.
1580 // Shell probably spit out an error message, sorry :(
1581 // Fall through to fgets()...
1588 // Fallback... we'll have no editing controls, EWWW
1589 if ( feof( STDIN
) ) {
1594 return fgets( STDIN
, 1024 );
1598 * Get the terminal size as a two-element array where the first element
1599 * is the width (number of columns) and the second element is the height
1604 public static function getTermSize() {
1605 $default = [ 80, 50 ];
1606 if ( wfIsWindows() ) {
1609 if ( Shell
::isDisabled() ) {
1612 // It's possible to get the screen size with VT-100 terminal escapes,
1613 // but reading the responses is not possible without setting raw mode
1614 // (unless you want to require the user to press enter), and that
1615 // requires an ioctl(), which we can't do. So we have to shell out to
1616 // something that can do the relevant syscalls. There are a few
1617 // options. Linux and Mac OS X both have "stty size" which does the
1619 $result = Shell
::command( 'stty', 'size' )
1621 if ( $result->getExitCode() !== 0 ) {
1624 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1627 return [ intval( $m[2] ), intval( $m[1] ) ];
1631 * Call this to set up the autoloader to allow classes to be used from the
1634 public static function requireTestsAutoloader() {
1635 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1640 * Fake maintenance wrapper, mostly used for the web installer/updater
1642 class FakeMaintenance
extends Maintenance
{
1643 protected $mSelf = "FakeMaintenanceScript";
1645 public function execute() {
1651 * Class for scripts that perform database maintenance and want to log the
1652 * update in `updatelog` so we can later skip it
1654 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1655 public function __construct() {
1656 parent
::__construct();
1657 $this->addOption( 'force', 'Run the update even if it was completed already' );
1658 $this->setBatchSize( 200 );
1661 public function execute() {
1662 $db = $this->getDB( DB_MASTER
);
1663 $key = $this->getUpdateKey();
1665 if ( !$this->hasOption( 'force' )
1666 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1668 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1673 if ( !$this->doDBUpdates() ) {
1677 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1680 $this->output( $this->updatelogFailedMessage() . "\n" );
1687 * Message to show that the update was done already and was just skipped
1690 protected function updateSkippedMessage() {
1691 $key = $this->getUpdateKey();
1693 return "Update '{$key}' already logged as completed.";
1697 * Message to show that the update log was unable to log the completion of this update
1700 protected function updatelogFailedMessage() {
1701 $key = $this->getUpdateKey();
1703 return "Unable to log update '{$key}' as completed.";
1707 * Do the actual work. All child classes will need to implement this.
1708 * Return true to log the update as done or false (usually on failure).
1711 abstract protected function doDBUpdates();
1714 * Get the update key name to go in the update log table
1717 abstract protected function getUpdateKey();