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 Wikimedia\Rdbms\DBReplicationWaitError
;
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' );
37 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
41 use Wikimedia\Rdbms\IDatabase
;
42 use MediaWiki\Logger\LoggerFactory
;
43 use MediaWiki\MediaWikiServices
;
44 use Wikimedia\Rdbms\LBFactory
;
45 use Wikimedia\Rdbms\IMaintainableDatabase
;
48 * Abstract maintenance class for quickly writing and churning out
49 * maintenance scripts with minimal effort. All that _must_ be defined
50 * is the execute() method. See docs/maintenance.txt for more info
51 * and a quick demo of how to use it.
54 * @ingroup Maintenance
56 abstract class Maintenance
{
58 * Constants for DB access type
59 * @see Maintenance::getDbType()
65 // Const for getStdin()
66 const STDIN_ALL
= 'all';
68 // This is the desired params
69 protected $mParams = [];
71 // Array of mapping short parameters to long ones
72 protected $mShortParamsMap = [];
74 // Array of desired args
75 protected $mArgList = [];
77 // This is the list of options that were actually passed
78 protected $mOptions = [];
80 // This is the list of arguments that were actually passed
81 protected $mArgs = [];
83 // Name of the script currently running
86 // Special vars for params that are always used
87 protected $mQuiet = false;
88 protected $mDbUser, $mDbPass;
90 // A description of the script, children should change this via addDescription()
91 protected $mDescription = '';
93 // Have we already loaded our user input?
94 protected $mInputLoaded = false;
97 * Batch size. If a script supports this, they should set
98 * a default with setBatchSize()
102 protected $mBatchSize = null;
104 // Generic options added by addDefaultParams()
105 private $mGenericParameters = [];
106 // Generic options which might or not be supported by the script
107 private $mDependantParameters = [];
110 * Used by getDB() / setDB()
111 * @var IMaintainableDatabase
115 /** @var float UNIX timestamp */
116 private $lastReplicationWait = 0.0;
119 * Used when creating separate schema files.
125 * Accessible via getConfig()
132 * @see Maintenance::requireExtension
135 private $requiredExtensions = [];
138 * Used to read the options in the order they were passed.
139 * Useful for option chaining (Ex. dumpBackup.php). It will
140 * be an empty array if the options are passed in through
141 * loadParamsAndArgs( $self, $opts, $args ).
143 * This is an array of arrays where
144 * 0 => the option and 1 => parameter value.
148 public $orderedOptions = [];
151 * Default constructor. Children should call this *first* if implementing
152 * their own constructors
154 public function __construct() {
155 // Setup $IP, using MW_INSTALL_PATH if it exists
157 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
158 ?
getenv( 'MW_INSTALL_PATH' )
159 : realpath( __DIR__
. '/..' );
161 $this->addDefaultParams();
162 register_shutdown_function( [ $this, 'outputChanneled' ], false );
166 * Should we execute the maintenance script, or just allow it to be included
167 * as a standalone class? It checks that the call stack only includes this
168 * function and "requires" (meaning was called from the file scope)
172 public static function shouldExecute() {
173 global $wgCommandLineMode;
175 if ( !function_exists( 'debug_backtrace' ) ) {
176 // If someone has a better idea...
177 return $wgCommandLineMode;
180 $bt = debug_backtrace();
181 $count = count( $bt );
183 return false; // sanity
185 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
186 return false; // last call should be to this function
188 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
189 for ( $i = 1; $i < $count; $i++
) {
190 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
191 return false; // previous calls should all be "requires"
199 * Do the actual work. All child classes will need to implement this
201 abstract public function execute();
204 * Add a parameter to the script. Will be displayed on --help
205 * with the associated description
207 * @param string $name The name of the param (help, version, etc)
208 * @param string $description The description of the param to show on --help
209 * @param bool $required Is the param required?
210 * @param bool $withArg Is an argument required with this option?
211 * @param string|bool $shortName Character to use as short name
212 * @param bool $multiOccurrence Can this option be passed multiple times?
214 protected function addOption( $name, $description, $required = false,
215 $withArg = false, $shortName = false, $multiOccurrence = false
217 $this->mParams
[$name] = [
218 'desc' => $description,
219 'require' => $required,
220 'withArg' => $withArg,
221 'shortName' => $shortName,
222 'multiOccurrence' => $multiOccurrence
225 if ( $shortName !== false ) {
226 $this->mShortParamsMap
[$shortName] = $name;
231 * Checks to see if a particular param exists.
232 * @param string $name The name of the param
235 protected function hasOption( $name ) {
236 return isset( $this->mOptions
[$name] );
240 * Get an option, or return the default.
242 * If the option was added to support multiple occurrences,
243 * this will return an array.
245 * @param string $name The name of the param
246 * @param mixed $default Anything you want, default null
249 protected function getOption( $name, $default = null ) {
250 if ( $this->hasOption( $name ) ) {
251 return $this->mOptions
[$name];
253 // Set it so we don't have to provide the default again
254 $this->mOptions
[$name] = $default;
256 return $this->mOptions
[$name];
261 * Add some args that are needed
262 * @param string $arg Name of the arg, like 'start'
263 * @param string $description Short description of the arg
264 * @param bool $required Is this required?
266 protected function addArg( $arg, $description, $required = true ) {
267 $this->mArgList
[] = [
269 'desc' => $description,
270 'require' => $required
275 * Remove an option. Useful for removing options that won't be used in your script.
276 * @param string $name The option to remove.
278 protected function deleteOption( $name ) {
279 unset( $this->mParams
[$name] );
283 * Set the description text.
284 * @param string $text The text of the description
286 protected function addDescription( $text ) {
287 $this->mDescription
= $text;
291 * Does a given argument exist?
292 * @param int $argId The integer value (from zero) for the arg
295 protected function hasArg( $argId = 0 ) {
296 return isset( $this->mArgs
[$argId] );
301 * @param int $argId The integer value (from zero) for the arg
302 * @param mixed $default The default if it doesn't exist
305 protected function getArg( $argId = 0, $default = null ) {
306 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
316 protected function getBatchSize() {
317 return $this->mBatchSize
;
321 * Set the batch size.
322 * @param int $s The number of operations to do in a batch
324 protected function setBatchSize( $s = 0 ) {
325 $this->mBatchSize
= $s;
327 // If we support $mBatchSize, show the option.
328 // Used to be in addDefaultParams, but in order for that to
329 // work, subclasses would have to call this function in the constructor
330 // before they called parent::__construct which is just weird
331 // (and really wasn't done).
332 if ( $this->mBatchSize
) {
333 $this->addOption( 'batch-size', 'Run this many operations ' .
334 'per batch, default: ' . $this->mBatchSize
, false, true );
335 if ( isset( $this->mParams
['batch-size'] ) ) {
336 // This seems a little ugly...
337 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
343 * Get the script's name
346 public function getName() {
351 * Return input from stdin.
352 * @param int $len The number of bytes to read. If null, just return the handle.
353 * Maintenance::STDIN_ALL returns the full length
356 protected function getStdin( $len = null ) {
357 if ( $len == self
::STDIN_ALL
) {
358 return file_get_contents( 'php://stdin' );
360 $f = fopen( 'php://stdin', 'rt' );
364 $input = fgets( $f, $len );
367 return rtrim( $input );
373 public function isQuiet() {
374 return $this->mQuiet
;
378 * Throw some output to the user. Scripts can call this with no fears,
379 * as we handle all --quiet stuff here
380 * @param string $out The text to show to the user
381 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
383 protected function output( $out, $channel = null ) {
384 if ( $this->mQuiet
) {
387 if ( $channel === null ) {
388 $this->cleanupChanneled();
391 $out = preg_replace( '/\n\z/', '', $out );
392 $this->outputChanneled( $out, $channel );
397 * Throw an error to the user. Doesn't respect --quiet, so don't use
398 * this for non-error output
399 * @param string $err The error to display
400 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
402 protected function error( $err, $die = 0 ) {
403 if ( intval( $die ) !== 0 ) {
404 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
405 $this->fatalError( $err, intval( $die ) );
407 $this->outputChanneled( false );
408 if ( PHP_SAPI
== 'cli' ) {
409 fwrite( STDERR
, $err . "\n" );
416 * Output a message and terminate the current script.
418 * @param string $msg Error message
419 * @param int $exitCode PHP exit status. Should be in range 1-254.
422 protected function fatalError( $msg, $exitCode = 1 ) {
423 $this->error( $msg );
427 private $atLineStart = true;
428 private $lastChannel = null;
431 * Clean up channeled output. Output a newline if necessary.
433 public function cleanupChanneled() {
434 if ( !$this->atLineStart
) {
436 $this->atLineStart
= true;
441 * Message outputter with channeled message support. Messages on the
442 * same channel are concatenated, but any intervening messages in another
443 * channel start a new line.
444 * @param string $msg The message without trailing newline
445 * @param string $channel Channel identifier or null for no
446 * channel. Channel comparison uses ===.
448 public function outputChanneled( $msg, $channel = null ) {
449 if ( $msg === false ) {
450 $this->cleanupChanneled();
455 // End the current line if necessary
456 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
462 $this->atLineStart
= false;
463 if ( $channel === null ) {
464 // For unchanneled messages, output trailing newline immediately
466 $this->atLineStart
= true;
468 $this->lastChannel
= $channel;
472 * Does the script need different DB access? By default, we give Maintenance
473 * scripts normal rights to the DB. Sometimes, a script needs admin rights
474 * access for a reason and sometimes they want no access. Subclasses should
475 * override and return one of the following values, as needed:
476 * Maintenance::DB_NONE - For no DB access at all
477 * Maintenance::DB_STD - For normal DB access, default
478 * Maintenance::DB_ADMIN - For admin DB access
481 public function getDbType() {
486 * Add the default parameters to the scripts
488 protected function addDefaultParams() {
489 # Generic (non script dependant) options:
491 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
492 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
493 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
494 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
495 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
498 'Set a specific memory limit for the script, '
499 . '"max" for no limit or "default" to avoid changing it'
501 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
502 "http://en.wikipedia.org. This is sometimes necessary because " .
503 "server name detection may fail in command line scripts.", false, true );
504 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
505 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
506 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
508 # Save generic options to display them separately in help
509 $this->mGenericParameters
= $this->mParams
;
511 # Script dependant options:
513 // If we support a DB, show the options
514 if ( $this->getDbType() > 0 ) {
515 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
516 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
519 # Save additional script dependant options to display
520 # Â them separately in help
521 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
528 public function getConfig() {
529 if ( $this->config
=== null ) {
530 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
533 return $this->config
;
538 * @param Config $config
540 public function setConfig( Config
$config ) {
541 $this->config
= $config;
545 * Indicate that the specified extension must be
546 * loaded before the script can run.
548 * This *must* be called in the constructor.
551 * @param string $name
553 protected function requireExtension( $name ) {
554 $this->requiredExtensions
[] = $name;
558 * Verify that the required extensions are installed
562 public function checkRequiredExtensions() {
563 $registry = ExtensionRegistry
::getInstance();
565 foreach ( $this->requiredExtensions
as $name ) {
566 if ( !$registry->isLoaded( $name ) ) {
572 $joined = implode( ', ', $missing );
573 $msg = "The following extensions are required to be installed "
574 . "for this script to run: $joined. Please enable them and then try again.";
575 $this->fatalError( $msg );
580 * Set triggers like when to try to run deferred updates
583 public function setAgentAndTriggers() {
584 if ( function_exists( 'posix_getpwuid' ) ) {
585 $agent = posix_getpwuid( posix_geteuid() )['name'];
589 $agent .= '@' . wfHostname();
591 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
592 // Add a comment for easy SHOW PROCESSLIST interpretation
593 $lbFactory->setAgentName(
594 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
596 self
::setLBFactoryTriggers( $lbFactory );
600 * @param LBFactory $LBFactory
603 public static function setLBFactoryTriggers( LBFactory
$LBFactory ) {
604 // Hook into period lag checks which often happen in long-running scripts
605 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
606 $lbFactory->setWaitForReplicationListener(
609 global $wgCommandLineMode;
610 // Check config in case of JobRunner and unit tests
611 if ( $wgCommandLineMode ) {
612 DeferredUpdates
::tryOpportunisticExecute( 'run' );
616 // Check for other windows to run them. A script may read or do a few writes
617 // to the master but mostly be writing to something else, like a file store.
618 $lbFactory->getMainLB()->setTransactionListener(
620 function ( $trigger ) {
621 global $wgCommandLineMode;
622 // Check config in case of JobRunner and unit tests
623 if ( $wgCommandLineMode && $trigger === IDatabase
::TRIGGER_COMMIT
) {
624 DeferredUpdates
::tryOpportunisticExecute( 'run' );
631 * Run a child maintenance script. Pass all of the current arguments
633 * @param string $maintClass A name of a child maintenance class
634 * @param string $classFile Full path of where the child is
635 * @return Maintenance
637 public function runChild( $maintClass, $classFile = null ) {
638 // Make sure the class is loaded first
639 if ( !class_exists( $maintClass ) ) {
641 require_once $classFile;
643 if ( !class_exists( $maintClass ) ) {
644 $this->error( "Cannot spawn child: $maintClass" );
649 * @var $child Maintenance
651 $child = new $maintClass();
652 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
653 if ( !is_null( $this->mDb
) ) {
654 $child->setDB( $this->mDb
);
661 * Do some sanity checking and basic setup
663 public function setup() {
664 global $IP, $wgCommandLineMode, $wgRequestTime;
666 # Abort if called from a web server
667 if ( PHP_SAPI
!== 'cli' ) {
668 $this->fatalError( 'This script must be run from the command line' );
671 if ( $IP === null ) {
672 $this->fatalError( "\$IP not set, aborting!\n" .
673 '(Did you forget to call parent::__construct() in your maintenance script?)' );
676 # Make sure we can handle script parameters
677 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
678 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
681 // Send PHP warnings and errors to stderr instead of stdout.
682 // This aids in diagnosing problems, while keeping messages
683 // out of redirected output.
684 if ( ini_get( 'display_errors' ) ) {
685 ini_set( 'display_errors', 'stderr' );
688 $this->loadParamsAndArgs();
691 # Set the memory limit
692 # Note we need to set it again later in cache LocalSettings changed it
693 $this->adjustMemoryLimit();
695 # Set max execution time to 0 (no limit). PHP.net says that
696 # "When running PHP from the command line the default setting is 0."
697 # But sometimes this doesn't seem to be the case.
698 ini_set( 'max_execution_time', 0 );
700 $wgRequestTime = microtime( true );
702 # Define us as being in MediaWiki
703 define( 'MEDIAWIKI', true );
705 $wgCommandLineMode = true;
707 # Turn off output buffering if it's on
708 while ( ob_get_level() > 0 ) {
712 $this->validateParamsAndArgs();
716 * Normally we disable the memory_limit when running admin scripts.
717 * Some scripts may wish to actually set a limit, however, to avoid
718 * blowing up unexpectedly. We also support a --memory-limit option,
719 * to allow sysadmins to explicitly set one if they'd prefer to override
720 * defaults (or for people using Suhosin which yells at you for trying
721 * to disable the limits)
724 public function memoryLimit() {
725 $limit = $this->getOption( 'memory-limit', 'max' );
726 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
731 * Adjusts PHP's memory limit to better suit our needs, if needed.
733 protected function adjustMemoryLimit() {
734 $limit = $this->memoryLimit();
735 if ( $limit == 'max' ) {
736 $limit = -1; // no memory limit
738 if ( $limit != 'default' ) {
739 ini_set( 'memory_limit', $limit );
744 * Activate the profiler (assuming $wgProfiler is set)
746 protected function activateProfiler() {
747 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
749 $output = $this->getOption( 'profiler' );
754 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
755 $class = $wgProfiler['class'];
756 /** @var Profiler $profiler */
757 $profiler = new $class(
758 [ 'sampling' => 1, 'output' => [ $output ] ]
760 +
[ 'threshold' => $wgProfileLimit ]
762 $profiler->setTemplated( true );
763 Profiler
::replaceStubInstance( $profiler );
766 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
767 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
768 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
772 * Clear all params and arguments.
774 public function clearParamsAndArgs() {
775 $this->mOptions
= [];
777 $this->mInputLoaded
= false;
781 * Load params and arguments from a given array
782 * of command-line arguments
787 public function loadWithArgv( $argv ) {
790 $this->orderedOptions
= [];
793 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
794 if ( $arg == '--' ) {
795 # End of options, remainder should be considered arguments
796 $arg = next( $argv );
797 while ( $arg !== false ) {
799 $arg = next( $argv );
802 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
804 $option = substr( $arg, 2 );
805 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
806 $param = next( $argv );
807 if ( $param === false ) {
808 $this->error( "\nERROR: $option parameter needs a value after it\n" );
809 $this->maybeHelp( true );
812 $this->setParam( $options, $option, $param );
814 $bits = explode( '=', $option, 2 );
815 if ( count( $bits ) > 1 ) {
822 $this->setParam( $options, $option, $param );
824 } elseif ( $arg == '-' ) {
825 # Lonely "-", often used to indicate stdin or stdout.
827 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
829 $argLength = strlen( $arg );
830 for ( $p = 1; $p < $argLength; $p++
) {
832 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
833 $option = $this->mShortParamsMap
[$option];
836 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
837 $param = next( $argv );
838 if ( $param === false ) {
839 $this->error( "\nERROR: $option parameter needs a value after it\n" );
840 $this->maybeHelp( true );
842 $this->setParam( $options, $option, $param );
844 $this->setParam( $options, $option, 1 );
852 $this->mOptions
= $options;
853 $this->mArgs
= $args;
854 $this->loadSpecialVars();
855 $this->mInputLoaded
= true;
859 * Helper function used solely by loadParamsAndArgs
860 * to prevent code duplication
862 * This sets the param in the options array based on
863 * whether or not it can be specified multiple times.
866 * @param array $options
867 * @param string $option
868 * @param mixed $value
870 private function setParam( &$options, $option, $value ) {
871 $this->orderedOptions
[] = [ $option, $value ];
873 if ( isset( $this->mParams
[$option] ) ) {
874 $multi = $this->mParams
[$option]['multiOccurrence'];
878 $exists = array_key_exists( $option, $options );
879 if ( $multi && $exists ) {
880 $options[$option][] = $value;
881 } elseif ( $multi ) {
882 $options[$option] = [ $value ];
883 } elseif ( !$exists ) {
884 $options[$option] = $value;
886 $this->error( "\nERROR: $option parameter given twice\n" );
887 $this->maybeHelp( true );
892 * Process command line arguments
893 * $mOptions becomes an array with keys set to the option names
894 * $mArgs becomes a zero-based array containing the non-option arguments
896 * @param string $self The name of the script, if any
897 * @param array $opts An array of options, in form of key=>value
898 * @param array $args An array of command line arguments
900 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
901 # If we were given opts or args, set those and return early
903 $this->mSelf
= $self;
904 $this->mInputLoaded
= true;
907 $this->mOptions
= $opts;
908 $this->mInputLoaded
= true;
911 $this->mArgs
= $args;
912 $this->mInputLoaded
= true;
915 # If we've already loaded input (either by user values or from $argv)
916 # skip on loading it again. The array_shift() will corrupt values if
917 # it's run again and again
918 if ( $this->mInputLoaded
) {
919 $this->loadSpecialVars();
925 $this->mSelf
= $argv[0];
926 $this->loadWithArgv( array_slice( $argv, 1 ) );
930 * Run some validation checks on the params, etc
932 protected function validateParamsAndArgs() {
934 # Check to make sure we've got all the required options
935 foreach ( $this->mParams
as $opt => $info ) {
936 if ( $info['require'] && !$this->hasOption( $opt ) ) {
937 $this->error( "Param $opt required!" );
942 foreach ( $this->mArgList
as $k => $info ) {
943 if ( $info['require'] && !$this->hasArg( $k ) ) {
944 $this->error( 'Argument <' . $info['name'] . '> required!' );
950 $this->maybeHelp( true );
955 * Handle the special variables that are global to all scripts
957 protected function loadSpecialVars() {
958 if ( $this->hasOption( 'dbuser' ) ) {
959 $this->mDbUser
= $this->getOption( 'dbuser' );
961 if ( $this->hasOption( 'dbpass' ) ) {
962 $this->mDbPass
= $this->getOption( 'dbpass' );
964 if ( $this->hasOption( 'quiet' ) ) {
965 $this->mQuiet
= true;
967 if ( $this->hasOption( 'batch-size' ) ) {
968 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
973 * Maybe show the help.
974 * @param bool $force Whether to force the help to show, default false
976 protected function maybeHelp( $force = false ) {
977 if ( !$force && !$this->hasOption( 'help' ) ) {
981 $screenWidth = 80; // TODO: Calculate this!
983 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
985 ksort( $this->mParams
);
986 $this->mQuiet
= false;
989 if ( $this->mDescription
) {
990 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
992 $output = "\nUsage: php " . basename( $this->mSelf
);
994 // ... append parameters ...
995 if ( $this->mParams
) {
996 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
999 // ... and append arguments.
1000 if ( $this->mArgList
) {
1002 foreach ( $this->mArgList
as $k => $arg ) {
1003 if ( $arg['require'] ) {
1004 $output .= '<' . $arg['name'] . '>';
1006 $output .= '[' . $arg['name'] . ']';
1008 if ( $k < count( $this->mArgList
) - 1 ) {
1013 $this->output( "$output\n\n" );
1015 # TODO abstract some repetitive code below
1017 // Generic parameters
1018 $this->output( "Generic maintenance parameters:\n" );
1019 foreach ( $this->mGenericParameters
as $par => $info ) {
1020 if ( $info['shortName'] !== false ) {
1021 $par .= " (-{$info['shortName']})";
1024 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1025 "\n$tab$tab" ) . "\n"
1028 $this->output( "\n" );
1030 $scriptDependantParams = $this->mDependantParameters
;
1031 if ( count( $scriptDependantParams ) > 0 ) {
1032 $this->output( "Script dependant parameters:\n" );
1033 // Parameters description
1034 foreach ( $scriptDependantParams as $par => $info ) {
1035 if ( $info['shortName'] !== false ) {
1036 $par .= " (-{$info['shortName']})";
1039 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1040 "\n$tab$tab" ) . "\n"
1043 $this->output( "\n" );
1046 // Script specific parameters not defined on construction by
1047 // Maintenance::addDefaultParams()
1048 $scriptSpecificParams = array_diff_key(
1049 # all script parameters:
1051 # remove the Maintenance default parameters:
1052 $this->mGenericParameters
,
1053 $this->mDependantParameters
1055 if ( count( $scriptSpecificParams ) > 0 ) {
1056 $this->output( "Script specific parameters:\n" );
1057 // Parameters description
1058 foreach ( $scriptSpecificParams as $par => $info ) {
1059 if ( $info['shortName'] !== false ) {
1060 $par .= " (-{$info['shortName']})";
1063 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1064 "\n$tab$tab" ) . "\n"
1067 $this->output( "\n" );
1071 if ( count( $this->mArgList
) > 0 ) {
1072 $this->output( "Arguments:\n" );
1073 // Arguments description
1074 foreach ( $this->mArgList
as $info ) {
1075 $openChar = $info['require'] ?
'<' : '[';
1076 $closeChar = $info['require'] ?
'>' : ']';
1078 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1079 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1082 $this->output( "\n" );
1089 * Handle some last-minute setup here.
1091 public function finalSetup() {
1092 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1093 global $wgDBadminuser, $wgDBadminpassword;
1094 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1096 # Turn off output buffering again, it might have been turned on in the settings files
1097 if ( ob_get_level() ) {
1101 $wgCommandLineMode = true;
1103 # Override $wgServer
1104 if ( $this->hasOption( 'server' ) ) {
1105 $wgServer = $this->getOption( 'server', $wgServer );
1108 # If these were passed, use them
1109 if ( $this->mDbUser
) {
1110 $wgDBadminuser = $this->mDbUser
;
1112 if ( $this->mDbPass
) {
1113 $wgDBadminpassword = $this->mDbPass
;
1116 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1117 $wgDBuser = $wgDBadminuser;
1118 $wgDBpassword = $wgDBadminpassword;
1120 if ( $wgDBservers ) {
1122 * @var $wgDBservers array
1124 foreach ( $wgDBservers as $i => $server ) {
1125 $wgDBservers[$i]['user'] = $wgDBuser;
1126 $wgDBservers[$i]['password'] = $wgDBpassword;
1129 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1130 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1131 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1133 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1136 # Apply debug settings
1137 if ( $this->hasOption( 'mwdebug' ) ) {
1138 require __DIR__
. '/../includes/DevelopmentSettings.php';
1141 // Per-script profiling; useful for debugging
1142 $this->activateProfiler();
1144 $this->afterFinalSetup();
1146 $wgShowSQLErrors = true;
1148 MediaWiki\
suppressWarnings();
1149 set_time_limit( 0 );
1150 MediaWiki\restoreWarnings
();
1152 $this->adjustMemoryLimit();
1156 * Execute a callback function at the end of initialisation
1158 protected function afterFinalSetup() {
1159 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1160 call_user_func( MW_CMDLINE_CALLBACK
);
1165 * Potentially debug globals. Originally a feature only
1168 public function globals() {
1169 if ( $this->hasOption( 'globals' ) ) {
1170 print_r( $GLOBALS );
1175 * Generic setup for most installs. Returns the location of LocalSettings
1178 public function loadSettings() {
1179 global $wgCommandLineMode, $IP;
1181 if ( isset( $this->mOptions
['conf'] ) ) {
1182 $settingsFile = $this->mOptions
['conf'];
1183 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1184 $settingsFile = MW_CONFIG_FILE
;
1186 $settingsFile = "$IP/LocalSettings.php";
1188 if ( isset( $this->mOptions
['wiki'] ) ) {
1189 $bits = explode( '-', $this->mOptions
['wiki'] );
1190 if ( count( $bits ) == 1 ) {
1193 define( 'MW_DB', $bits[0] );
1194 define( 'MW_PREFIX', $bits[1] );
1197 if ( !is_readable( $settingsFile ) ) {
1198 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1199 "must exist and be readable in the source directory.\n" .
1200 "Use --conf to specify it." );
1202 $wgCommandLineMode = true;
1204 return $settingsFile;
1208 * Support function for cleaning up redundant text records
1209 * @param bool $delete Whether or not to actually delete the records
1210 * @author Rob Church <robchur@gmail.com>
1212 public function purgeRedundantText( $delete = true ) {
1213 # Data should come off the master, wrapped in a transaction
1214 $dbw = $this->getDB( DB_MASTER
);
1215 $this->beginTransaction( $dbw, __METHOD__
);
1217 # Get "active" text records from the revisions table
1219 $this->output( 'Searching for active text records in revisions table...' );
1220 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1221 foreach ( $res as $row ) {
1222 $cur[] = $row->rev_text_id
;
1224 $this->output( "done.\n" );
1226 # Get "active" text records from the archive table
1227 $this->output( 'Searching for active text records in archive table...' );
1228 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1229 foreach ( $res as $row ) {
1230 # old pre-MW 1.5 records can have null ar_text_id's.
1231 if ( $row->ar_text_id
!== null ) {
1232 $cur[] = $row->ar_text_id
;
1235 $this->output( "done.\n" );
1237 # Get the IDs of all text records not in these sets
1238 $this->output( 'Searching for inactive text records...' );
1239 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1240 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1242 foreach ( $res as $row ) {
1243 $old[] = $row->old_id
;
1245 $this->output( "done.\n" );
1247 # Inform the user of what we're going to do
1248 $count = count( $old );
1249 $this->output( "$count inactive items found.\n" );
1251 # Delete as appropriate
1252 if ( $delete && $count ) {
1253 $this->output( 'Deleting...' );
1254 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1255 $this->output( "done.\n" );
1259 $this->commitTransaction( $dbw, __METHOD__
);
1263 * Get the maintenance directory.
1266 protected function getDir() {
1271 * Returns a database to be used by current maintenance script. It can be set by setDB().
1272 * If not set, wfGetDB() will be used.
1273 * This function has the same parameters as wfGetDB()
1275 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1276 * @param array $groups default: empty array
1277 * @param string|bool $wiki default: current wiki
1278 * @return IMaintainableDatabase
1280 protected function getDB( $db, $groups = [], $wiki = false ) {
1281 if ( is_null( $this->mDb
) ) {
1282 return wfGetDB( $db, $groups, $wiki );
1289 * Sets database object to be returned by getDB().
1291 * @param IDatabase $db
1293 public function setDB( IDatabase
$db ) {
1298 * Begin a transcation on a DB
1300 * This method makes it clear that begin() is called from a maintenance script,
1301 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1303 * @param IDatabase $dbw
1304 * @param string $fname Caller name
1307 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1308 $dbw->begin( $fname );
1312 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1314 * This method makes it clear that commit() is called from a maintenance script,
1315 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1317 * @param IDatabase $dbw
1318 * @param string $fname Caller name
1319 * @return bool Whether the replica DB wait succeeded
1322 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1323 $dbw->commit( $fname );
1325 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1326 $lbFactory->waitForReplication(
1327 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1329 $this->lastReplicationWait
= microtime( true );
1332 } catch ( DBReplicationWaitError
$e ) {
1338 * Rollback the transcation on a DB handle
1340 * This method makes it clear that rollback() is called from a maintenance script,
1341 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1343 * @param IDatabase $dbw
1344 * @param string $fname Caller name
1347 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1348 $dbw->rollback( $fname );
1352 * Lock the search index
1353 * @param IMaintainableDatabase &$db
1355 private function lockSearchindex( $db ) {
1356 $write = [ 'searchindex' ];
1366 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1371 * @param IMaintainableDatabase &$db
1373 private function unlockSearchindex( $db ) {
1374 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1378 * Unlock and lock again
1379 * Since the lock is low-priority, queued reads will be able to complete
1380 * @param IMaintainableDatabase &$db
1382 private function relockSearchindex( $db ) {
1383 $this->unlockSearchindex( $db );
1384 $this->lockSearchindex( $db );
1388 * Perform a search index update with locking
1389 * @param int $maxLockTime The maximum time to keep the search index locked.
1390 * @param string $callback The function that will update the function.
1391 * @param IMaintainableDatabase $dbw
1392 * @param array $results
1394 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1398 if ( $maxLockTime ) {
1399 $this->output( " --- Waiting for lock ---" );
1400 $this->lockSearchindex( $dbw );
1402 $this->output( "\n" );
1405 # Loop through the results and do a search update
1406 foreach ( $results as $row ) {
1407 # Allow reads to be processed
1408 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1409 $this->output( " --- Relocking ---" );
1410 $this->relockSearchindex( $dbw );
1412 $this->output( "\n" );
1414 call_user_func( $callback, $dbw, $row );
1417 # Unlock searchindex
1418 if ( $maxLockTime ) {
1419 $this->output( " --- Unlocking --" );
1420 $this->unlockSearchindex( $dbw );
1421 $this->output( "\n" );
1426 * Update the searchindex table for a given pageid
1427 * @param IDatabase $dbw A database write handle
1428 * @param int $pageId The page ID to update.
1429 * @return null|string
1431 public function updateSearchIndexForPage( $dbw, $pageId ) {
1432 // Get current revision
1433 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1436 $titleObj = $rev->getTitle();
1437 $title = $titleObj->getPrefixedDBkey();
1438 $this->output( "$title..." );
1439 # Update searchindex
1440 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1442 $this->output( "\n" );
1449 * Count down from $seconds to zero on the terminal, with a one-second pause
1450 * between showing each number. If the maintenance script is in quiet mode,
1451 * this function does nothing.
1455 * @codeCoverageIgnore
1456 * @param int $seconds
1458 protected function countDown( $seconds ) {
1459 if ( $this->isQuiet() ) {
1462 for ( $i = $seconds; $i >= 0; $i-- ) {
1463 if ( $i != $seconds ) {
1464 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1466 $this->output( $i );
1471 $this->output( "\n" );
1475 * Wrapper for posix_isatty()
1476 * We default as considering stdin a tty (for nice readline methods)
1477 * but treating stout as not a tty to avoid color codes
1479 * @param mixed $fd File descriptor
1482 public static function posix_isatty( $fd ) {
1483 if ( !function_exists( 'posix_isatty' ) ) {
1486 return posix_isatty( $fd );
1491 * Prompt the console for input
1492 * @param string $prompt What to begin the line with, like '> '
1493 * @return string Response
1495 public static function readconsole( $prompt = '> ' ) {
1496 static $isatty = null;
1497 if ( is_null( $isatty ) ) {
1498 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1501 if ( $isatty && function_exists( 'readline' ) ) {
1502 return readline( $prompt );
1505 $st = self
::readlineEmulation( $prompt );
1507 if ( feof( STDIN
) ) {
1510 $st = fgets( STDIN
, 1024 );
1513 if ( $st === false ) {
1516 $resp = trim( $st );
1523 * Emulate readline()
1524 * @param string $prompt What to begin the line with, like '> '
1527 private static function readlineEmulation( $prompt ) {
1528 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1529 if ( !wfIsWindows() && $bash ) {
1531 $encPrompt = wfEscapeShellArg( $prompt );
1532 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1533 $encCommand = wfEscapeShellArg( $command );
1534 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1536 if ( $retval == 0 ) {
1538 } elseif ( $retval == 127 ) {
1539 // Couldn't execute bash even though we thought we saw it.
1540 // Shell probably spit out an error message, sorry :(
1541 // Fall through to fgets()...
1548 // Fallback... we'll have no editing controls, EWWW
1549 if ( feof( STDIN
) ) {
1554 return fgets( STDIN
, 1024 );
1558 * Get the terminal size as a two-element array where the first element
1559 * is the width (number of columns) and the second element is the height
1564 public static function getTermSize() {
1565 $default = [ 80, 50 ];
1566 if ( wfIsWindows() ) {
1569 // It's possible to get the screen size with VT-100 terminal escapes,
1570 // but reading the responses is not possible without setting raw mode
1571 // (unless you want to require the user to press enter), and that
1572 // requires an ioctl(), which we can't do. So we have to shell out to
1573 // something that can do the relevant syscalls. There are a few
1574 // options. Linux and Mac OS X both have "stty size" which does the
1577 $size = wfShellExec( 'stty size', $retval );
1578 if ( $retval !== 0 ) {
1581 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1584 return [ intval( $m[2] ), intval( $m[1] ) ];
1588 * Call this to set up the autoloader to allow classes to be used from the
1591 public static function requireTestsAutoloader() {
1592 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1597 * Fake maintenance wrapper, mostly used for the web installer/updater
1599 class FakeMaintenance
extends Maintenance
{
1600 protected $mSelf = "FakeMaintenanceScript";
1602 public function execute() {
1608 * Class for scripts that perform database maintenance and want to log the
1609 * update in `updatelog` so we can later skip it
1611 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1612 public function __construct() {
1613 parent
::__construct();
1614 $this->addOption( 'force', 'Run the update even if it was completed already' );
1615 $this->setBatchSize( 200 );
1618 public function execute() {
1619 $db = $this->getDB( DB_MASTER
);
1620 $key = $this->getUpdateKey();
1622 if ( !$this->hasOption( 'force' )
1623 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1625 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1630 if ( !$this->doDBUpdates() ) {
1634 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1637 $this->output( $this->updatelogFailedMessage() . "\n" );
1644 * Message to show that the update was done already and was just skipped
1647 protected function updateSkippedMessage() {
1648 $key = $this->getUpdateKey();
1650 return "Update '{$key}' already logged as completed.";
1654 * Message to show that the update log was unable to log the completion of this update
1657 protected function updatelogFailedMessage() {
1658 $key = $this->getUpdateKey();
1660 return "Unable to log update '{$key}' as completed.";
1664 * Do the actual work. All child classes will need to implement this.
1665 * Return true to log the update as done or false (usually on failure).
1668 abstract protected function doDBUpdates();
1671 * Get the update key name to go in the update log table
1674 abstract protected function getUpdateKey();