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.
53 * @author Chad Horohoe <chad@anyonecanedit.org>
55 * @ingroup Maintenance
57 abstract class Maintenance
{
59 * Constants for DB access type
60 * @see Maintenance::getDbType()
66 // Const for getStdin()
67 const STDIN_ALL
= 'all';
69 // This is the desired params
70 protected $mParams = [];
72 // Array of mapping short parameters to long ones
73 protected $mShortParamsMap = [];
75 // Array of desired args
76 protected $mArgList = [];
78 // This is the list of options that were actually passed
79 protected $mOptions = [];
81 // This is the list of arguments that were actually passed
82 protected $mArgs = [];
84 // Name of the script currently running
87 // Special vars for params that are always used
88 protected $mQuiet = false;
89 protected $mDbUser, $mDbPass;
91 // A description of the script, children should change this via addDescription()
92 protected $mDescription = '';
94 // Have we already loaded our user input?
95 protected $mInputLoaded = false;
98 * Batch size. If a script supports this, they should set
99 * a default with setBatchSize()
103 protected $mBatchSize = null;
105 // Generic options added by addDefaultParams()
106 private $mGenericParameters = [];
107 // Generic options which might or not be supported by the script
108 private $mDependantParameters = [];
111 * Used by getDB() / setDB()
112 * @var IMaintainableDatabase
116 /** @var float UNIX timestamp */
117 private $lastReplicationWait = 0.0;
120 * Used when creating separate schema files.
126 * Accessible via getConfig()
133 * @see Maintenance::requireExtension
136 private $requiredExtensions = [];
139 * Used to read the options in the order they were passed.
140 * Useful for option chaining (Ex. dumpBackup.php). It will
141 * be an empty array if the options are passed in through
142 * loadParamsAndArgs( $self, $opts, $args ).
144 * This is an array of arrays where
145 * 0 => the option and 1 => parameter value.
149 public $orderedOptions = [];
152 * Default constructor. Children should call this *first* if implementing
153 * their own constructors
155 public function __construct() {
156 // Setup $IP, using MW_INSTALL_PATH if it exists
158 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
159 ?
getenv( 'MW_INSTALL_PATH' )
160 : realpath( __DIR__
. '/..' );
162 $this->addDefaultParams();
163 register_shutdown_function( [ $this, 'outputChanneled' ], false );
167 * Should we execute the maintenance script, or just allow it to be included
168 * as a standalone class? It checks that the call stack only includes this
169 * function and "requires" (meaning was called from the file scope)
173 public static function shouldExecute() {
174 global $wgCommandLineMode;
176 if ( !function_exists( 'debug_backtrace' ) ) {
177 // If someone has a better idea...
178 return $wgCommandLineMode;
181 $bt = debug_backtrace();
182 $count = count( $bt );
184 return false; // sanity
186 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
187 return false; // last call should be to this function
189 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
190 for ( $i = 1; $i < $count; $i++
) {
191 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
192 return false; // previous calls should all be "requires"
200 * Do the actual work. All child classes will need to implement this
202 abstract public function execute();
205 * Add a parameter to the script. Will be displayed on --help
206 * with the associated description
208 * @param string $name The name of the param (help, version, etc)
209 * @param string $description The description of the param to show on --help
210 * @param bool $required Is the param required?
211 * @param bool $withArg Is an argument required with this option?
212 * @param string|bool $shortName Character to use as short name
213 * @param bool $multiOccurrence Can this option be passed multiple times?
215 protected function addOption( $name, $description, $required = false,
216 $withArg = false, $shortName = false, $multiOccurrence = false
218 $this->mParams
[$name] = [
219 'desc' => $description,
220 'require' => $required,
221 'withArg' => $withArg,
222 'shortName' => $shortName,
223 'multiOccurrence' => $multiOccurrence
226 if ( $shortName !== false ) {
227 $this->mShortParamsMap
[$shortName] = $name;
232 * Checks to see if a particular param exists.
233 * @param string $name The name of the param
236 protected function hasOption( $name ) {
237 return isset( $this->mOptions
[$name] );
241 * Get an option, or return the default.
243 * If the option was added to support multiple occurrences,
244 * this will return an array.
246 * @param string $name The name of the param
247 * @param mixed $default Anything you want, default null
250 protected function getOption( $name, $default = null ) {
251 if ( $this->hasOption( $name ) ) {
252 return $this->mOptions
[$name];
254 // Set it so we don't have to provide the default again
255 $this->mOptions
[$name] = $default;
257 return $this->mOptions
[$name];
262 * Add some args that are needed
263 * @param string $arg Name of the arg, like 'start'
264 * @param string $description Short description of the arg
265 * @param bool $required Is this required?
267 protected function addArg( $arg, $description, $required = true ) {
268 $this->mArgList
[] = [
270 'desc' => $description,
271 'require' => $required
276 * Remove an option. Useful for removing options that won't be used in your script.
277 * @param string $name The option to remove.
279 protected function deleteOption( $name ) {
280 unset( $this->mParams
[$name] );
284 * Set the description text.
285 * @param string $text The text of the description
287 protected function addDescription( $text ) {
288 $this->mDescription
= $text;
292 * Does a given argument exist?
293 * @param int $argId The integer value (from zero) for the arg
296 protected function hasArg( $argId = 0 ) {
297 return isset( $this->mArgs
[$argId] );
302 * @param int $argId The integer value (from zero) for the arg
303 * @param mixed $default The default if it doesn't exist
306 protected function getArg( $argId = 0, $default = null ) {
307 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
317 protected function getBatchSize() {
318 return $this->mBatchSize
;
322 * Set the batch size.
323 * @param int $s The number of operations to do in a batch
325 protected function setBatchSize( $s = 0 ) {
326 $this->mBatchSize
= $s;
328 // If we support $mBatchSize, show the option.
329 // Used to be in addDefaultParams, but in order for that to
330 // work, subclasses would have to call this function in the constructor
331 // before they called parent::__construct which is just weird
332 // (and really wasn't done).
333 if ( $this->mBatchSize
) {
334 $this->addOption( 'batch-size', 'Run this many operations ' .
335 'per batch, default: ' . $this->mBatchSize
, false, true );
336 if ( isset( $this->mParams
['batch-size'] ) ) {
337 // This seems a little ugly...
338 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
344 * Get the script's name
347 public function getName() {
352 * Return input from stdin.
353 * @param int $len The number of bytes to read. If null, just return the handle.
354 * Maintenance::STDIN_ALL returns the full length
357 protected function getStdin( $len = null ) {
358 if ( $len == self
::STDIN_ALL
) {
359 return file_get_contents( 'php://stdin' );
361 $f = fopen( 'php://stdin', 'rt' );
365 $input = fgets( $f, $len );
368 return rtrim( $input );
374 public function isQuiet() {
375 return $this->mQuiet
;
379 * Throw some output to the user. Scripts can call this with no fears,
380 * as we handle all --quiet stuff here
381 * @param string $out The text to show to the user
382 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
384 protected function output( $out, $channel = null ) {
385 if ( $this->mQuiet
) {
388 if ( $channel === null ) {
389 $this->cleanupChanneled();
392 $out = preg_replace( '/\n\z/', '', $out );
393 $this->outputChanneled( $out, $channel );
398 * Throw an error to the user. Doesn't respect --quiet, so don't use
399 * this for non-error output
400 * @param string $err The error to display
401 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
403 protected function error( $err, $die = 0 ) {
404 if ( intval( $die ) !== 0 ) {
405 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
406 $this->fatalError( $err, intval( $die ) );
408 $this->outputChanneled( false );
409 if ( PHP_SAPI
== 'cli' ) {
410 fwrite( STDERR
, $err . "\n" );
417 * Output a message and terminate the current script.
419 * @param string $msg Error message
420 * @param int $exitCode PHP exit status. Should be in range 1-254.
423 protected function fatalError( $msg, $exitCode = 1 ) {
424 $this->error( $msg );
428 private $atLineStart = true;
429 private $lastChannel = null;
432 * Clean up channeled output. Output a newline if necessary.
434 public function cleanupChanneled() {
435 if ( !$this->atLineStart
) {
437 $this->atLineStart
= true;
442 * Message outputter with channeled message support. Messages on the
443 * same channel are concatenated, but any intervening messages in another
444 * channel start a new line.
445 * @param string $msg The message without trailing newline
446 * @param string $channel Channel identifier or null for no
447 * channel. Channel comparison uses ===.
449 public function outputChanneled( $msg, $channel = null ) {
450 if ( $msg === false ) {
451 $this->cleanupChanneled();
456 // End the current line if necessary
457 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
463 $this->atLineStart
= false;
464 if ( $channel === null ) {
465 // For unchanneled messages, output trailing newline immediately
467 $this->atLineStart
= true;
469 $this->lastChannel
= $channel;
473 * Does the script need different DB access? By default, we give Maintenance
474 * scripts normal rights to the DB. Sometimes, a script needs admin rights
475 * access for a reason and sometimes they want no access. Subclasses should
476 * override and return one of the following values, as needed:
477 * Maintenance::DB_NONE - For no DB access at all
478 * Maintenance::DB_STD - For normal DB access, default
479 * Maintenance::DB_ADMIN - For admin DB access
482 public function getDbType() {
487 * Add the default parameters to the scripts
489 protected function addDefaultParams() {
490 # Generic (non script dependant) options:
492 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
493 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
494 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
495 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
496 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
499 'Set a specific memory limit for the script, '
500 . '"max" for no limit or "default" to avoid changing it'
502 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
503 "http://en.wikipedia.org. This is sometimes necessary because " .
504 "server name detection may fail in command line scripts.", false, true );
505 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
507 # Save generic options to display them separately in help
508 $this->mGenericParameters
= $this->mParams
;
510 # Script dependant options:
512 // If we support a DB, show the options
513 if ( $this->getDbType() > 0 ) {
514 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
515 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
518 # Save additional script dependant options to display
519 # Â them separately in help
520 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
527 public function getConfig() {
528 if ( $this->config
=== null ) {
529 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
532 return $this->config
;
537 * @param Config $config
539 public function setConfig( Config
$config ) {
540 $this->config
= $config;
544 * Indicate that the specified extension must be
545 * loaded before the script can run.
547 * This *must* be called in the constructor.
550 * @param string $name
552 protected function requireExtension( $name ) {
553 $this->requiredExtensions
[] = $name;
557 * Verify that the required extensions are installed
561 public function checkRequiredExtensions() {
562 $registry = ExtensionRegistry
::getInstance();
564 foreach ( $this->requiredExtensions
as $name ) {
565 if ( !$registry->isLoaded( $name ) ) {
571 $joined = implode( ', ', $missing );
572 $msg = "The following extensions are required to be installed "
573 . "for this script to run: $joined. Please enable them and then try again.";
574 $this->fatalError( $msg );
579 * Set triggers like when to try to run deferred updates
582 public function setAgentAndTriggers() {
583 if ( function_exists( 'posix_getpwuid' ) ) {
584 $agent = posix_getpwuid( posix_geteuid() )['name'];
588 $agent .= '@' . wfHostname();
590 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
591 // Add a comment for easy SHOW PROCESSLIST interpretation
592 $lbFactory->setAgentName(
593 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
595 self
::setLBFactoryTriggers( $lbFactory );
599 * @param LBFactory $LBFactory
602 public static function setLBFactoryTriggers( LBFactory
$LBFactory ) {
603 // Hook into period lag checks which often happen in long-running scripts
604 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
605 $lbFactory->setWaitForReplicationListener(
608 global $wgCommandLineMode;
609 // Check config in case of JobRunner and unit tests
610 if ( $wgCommandLineMode ) {
611 DeferredUpdates
::tryOpportunisticExecute( 'run' );
615 // Check for other windows to run them. A script may read or do a few writes
616 // to the master but mostly be writing to something else, like a file store.
617 $lbFactory->getMainLB()->setTransactionListener(
619 function ( $trigger ) {
620 global $wgCommandLineMode;
621 // Check config in case of JobRunner and unit tests
622 if ( $wgCommandLineMode && $trigger === IDatabase
::TRIGGER_COMMIT
) {
623 DeferredUpdates
::tryOpportunisticExecute( 'run' );
630 * Run a child maintenance script. Pass all of the current arguments
632 * @param string $maintClass A name of a child maintenance class
633 * @param string $classFile Full path of where the child is
634 * @return Maintenance
636 public function runChild( $maintClass, $classFile = null ) {
637 // Make sure the class is loaded first
638 if ( !class_exists( $maintClass ) ) {
640 require_once $classFile;
642 if ( !class_exists( $maintClass ) ) {
643 $this->error( "Cannot spawn child: $maintClass" );
648 * @var $child Maintenance
650 $child = new $maintClass();
651 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
652 if ( !is_null( $this->mDb
) ) {
653 $child->setDB( $this->mDb
);
660 * Do some sanity checking and basic setup
662 public function setup() {
663 global $IP, $wgCommandLineMode, $wgRequestTime;
665 # Abort if called from a web server
666 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
667 $this->fatalError( 'This script must be run from the command line' );
670 if ( $IP === null ) {
671 $this->fatalError( "\$IP not set, aborting!\n" .
672 '(Did you forget to call parent::__construct() in your maintenance script?)' );
675 # Make sure we can handle script parameters
676 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
677 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
680 // Send PHP warnings and errors to stderr instead of stdout.
681 // This aids in diagnosing problems, while keeping messages
682 // out of redirected output.
683 if ( ini_get( 'display_errors' ) ) {
684 ini_set( 'display_errors', 'stderr' );
687 $this->loadParamsAndArgs();
690 # Set the memory limit
691 # Note we need to set it again later in cache LocalSettings changed it
692 $this->adjustMemoryLimit();
694 # Set max execution time to 0 (no limit). PHP.net says that
695 # "When running PHP from the command line the default setting is 0."
696 # But sometimes this doesn't seem to be the case.
697 ini_set( 'max_execution_time', 0 );
699 $wgRequestTime = microtime( true );
701 # Define us as being in MediaWiki
702 define( 'MEDIAWIKI', true );
704 $wgCommandLineMode = true;
706 # Turn off output buffering if it's on
707 while ( ob_get_level() > 0 ) {
711 $this->validateParamsAndArgs();
715 * Normally we disable the memory_limit when running admin scripts.
716 * Some scripts may wish to actually set a limit, however, to avoid
717 * blowing up unexpectedly. We also support a --memory-limit option,
718 * to allow sysadmins to explicitly set one if they'd prefer to override
719 * defaults (or for people using Suhosin which yells at you for trying
720 * to disable the limits)
723 public function memoryLimit() {
724 $limit = $this->getOption( 'memory-limit', 'max' );
725 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
730 * Adjusts PHP's memory limit to better suit our needs, if needed.
732 protected function adjustMemoryLimit() {
733 $limit = $this->memoryLimit();
734 if ( $limit == 'max' ) {
735 $limit = -1; // no memory limit
737 if ( $limit != 'default' ) {
738 ini_set( 'memory_limit', $limit );
743 * Activate the profiler (assuming $wgProfiler is set)
745 protected function activateProfiler() {
746 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
748 $output = $this->getOption( 'profiler' );
753 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
754 $class = $wgProfiler['class'];
755 /** @var Profiler $profiler */
756 $profiler = new $class(
757 [ 'sampling' => 1, 'output' => [ $output ] ]
759 +
[ 'threshold' => $wgProfileLimit ]
761 $profiler->setTemplated( true );
762 Profiler
::replaceStubInstance( $profiler );
765 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
766 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
767 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
771 * Clear all params and arguments.
773 public function clearParamsAndArgs() {
774 $this->mOptions
= [];
776 $this->mInputLoaded
= false;
780 * Load params and arguments from a given array
781 * of command-line arguments
786 public function loadWithArgv( $argv ) {
789 $this->orderedOptions
= [];
792 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
793 if ( $arg == '--' ) {
794 # End of options, remainder should be considered arguments
795 $arg = next( $argv );
796 while ( $arg !== false ) {
798 $arg = next( $argv );
801 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
803 $option = substr( $arg, 2 );
804 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
805 $param = next( $argv );
806 if ( $param === false ) {
807 $this->error( "\nERROR: $option parameter needs a value after it\n" );
808 $this->maybeHelp( true );
811 $this->setParam( $options, $option, $param );
813 $bits = explode( '=', $option, 2 );
814 if ( count( $bits ) > 1 ) {
821 $this->setParam( $options, $option, $param );
823 } elseif ( $arg == '-' ) {
824 # Lonely "-", often used to indicate stdin or stdout.
826 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
828 $argLength = strlen( $arg );
829 for ( $p = 1; $p < $argLength; $p++
) {
831 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
832 $option = $this->mShortParamsMap
[$option];
835 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
836 $param = next( $argv );
837 if ( $param === false ) {
838 $this->error( "\nERROR: $option parameter needs a value after it\n" );
839 $this->maybeHelp( true );
841 $this->setParam( $options, $option, $param );
843 $this->setParam( $options, $option, 1 );
851 $this->mOptions
= $options;
852 $this->mArgs
= $args;
853 $this->loadSpecialVars();
854 $this->mInputLoaded
= true;
858 * Helper function used solely by loadParamsAndArgs
859 * to prevent code duplication
861 * This sets the param in the options array based on
862 * whether or not it can be specified multiple times.
865 * @param array $options
866 * @param string $option
867 * @param mixed $value
869 private function setParam( &$options, $option, $value ) {
870 $this->orderedOptions
[] = [ $option, $value ];
872 if ( isset( $this->mParams
[$option] ) ) {
873 $multi = $this->mParams
[$option]['multiOccurrence'];
877 $exists = array_key_exists( $option, $options );
878 if ( $multi && $exists ) {
879 $options[$option][] = $value;
880 } elseif ( $multi ) {
881 $options[$option] = [ $value ];
882 } elseif ( !$exists ) {
883 $options[$option] = $value;
885 $this->error( "\nERROR: $option parameter given twice\n" );
886 $this->maybeHelp( true );
891 * Process command line arguments
892 * $mOptions becomes an array with keys set to the option names
893 * $mArgs becomes a zero-based array containing the non-option arguments
895 * @param string $self The name of the script, if any
896 * @param array $opts An array of options, in form of key=>value
897 * @param array $args An array of command line arguments
899 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
900 # If we were given opts or args, set those and return early
902 $this->mSelf
= $self;
903 $this->mInputLoaded
= true;
906 $this->mOptions
= $opts;
907 $this->mInputLoaded
= true;
910 $this->mArgs
= $args;
911 $this->mInputLoaded
= true;
914 # If we've already loaded input (either by user values or from $argv)
915 # skip on loading it again. The array_shift() will corrupt values if
916 # it's run again and again
917 if ( $this->mInputLoaded
) {
918 $this->loadSpecialVars();
924 $this->mSelf
= $argv[0];
925 $this->loadWithArgv( array_slice( $argv, 1 ) );
929 * Run some validation checks on the params, etc
931 protected function validateParamsAndArgs() {
933 # Check to make sure we've got all the required options
934 foreach ( $this->mParams
as $opt => $info ) {
935 if ( $info['require'] && !$this->hasOption( $opt ) ) {
936 $this->error( "Param $opt required!" );
941 foreach ( $this->mArgList
as $k => $info ) {
942 if ( $info['require'] && !$this->hasArg( $k ) ) {
943 $this->error( 'Argument <' . $info['name'] . '> required!' );
949 $this->maybeHelp( true );
954 * Handle the special variables that are global to all scripts
956 protected function loadSpecialVars() {
957 if ( $this->hasOption( 'dbuser' ) ) {
958 $this->mDbUser
= $this->getOption( 'dbuser' );
960 if ( $this->hasOption( 'dbpass' ) ) {
961 $this->mDbPass
= $this->getOption( 'dbpass' );
963 if ( $this->hasOption( 'quiet' ) ) {
964 $this->mQuiet
= true;
966 if ( $this->hasOption( 'batch-size' ) ) {
967 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
972 * Maybe show the help.
973 * @param bool $force Whether to force the help to show, default false
975 protected function maybeHelp( $force = false ) {
976 if ( !$force && !$this->hasOption( 'help' ) ) {
980 $screenWidth = 80; // TODO: Calculate this!
982 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
984 ksort( $this->mParams
);
985 $this->mQuiet
= false;
988 if ( $this->mDescription
) {
989 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
991 $output = "\nUsage: php " . basename( $this->mSelf
);
993 // ... append parameters ...
994 if ( $this->mParams
) {
995 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
998 // ... and append arguments.
999 if ( $this->mArgList
) {
1001 foreach ( $this->mArgList
as $k => $arg ) {
1002 if ( $arg['require'] ) {
1003 $output .= '<' . $arg['name'] . '>';
1005 $output .= '[' . $arg['name'] . ']';
1007 if ( $k < count( $this->mArgList
) - 1 ) {
1012 $this->output( "$output\n\n" );
1014 # TODO abstract some repetitive code below
1016 // Generic parameters
1017 $this->output( "Generic maintenance parameters:\n" );
1018 foreach ( $this->mGenericParameters
as $par => $info ) {
1019 if ( $info['shortName'] !== false ) {
1020 $par .= " (-{$info['shortName']})";
1023 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1024 "\n$tab$tab" ) . "\n"
1027 $this->output( "\n" );
1029 $scriptDependantParams = $this->mDependantParameters
;
1030 if ( count( $scriptDependantParams ) > 0 ) {
1031 $this->output( "Script dependant parameters:\n" );
1032 // Parameters description
1033 foreach ( $scriptDependantParams as $par => $info ) {
1034 if ( $info['shortName'] !== false ) {
1035 $par .= " (-{$info['shortName']})";
1038 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1039 "\n$tab$tab" ) . "\n"
1042 $this->output( "\n" );
1045 // Script specific parameters not defined on construction by
1046 // Maintenance::addDefaultParams()
1047 $scriptSpecificParams = array_diff_key(
1048 # all script parameters:
1050 # remove the Maintenance default parameters:
1051 $this->mGenericParameters
,
1052 $this->mDependantParameters
1054 if ( count( $scriptSpecificParams ) > 0 ) {
1055 $this->output( "Script specific parameters:\n" );
1056 // Parameters description
1057 foreach ( $scriptSpecificParams as $par => $info ) {
1058 if ( $info['shortName'] !== false ) {
1059 $par .= " (-{$info['shortName']})";
1062 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1063 "\n$tab$tab" ) . "\n"
1066 $this->output( "\n" );
1070 if ( count( $this->mArgList
) > 0 ) {
1071 $this->output( "Arguments:\n" );
1072 // Arguments description
1073 foreach ( $this->mArgList
as $info ) {
1074 $openChar = $info['require'] ?
'<' : '[';
1075 $closeChar = $info['require'] ?
'>' : ']';
1077 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1078 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1081 $this->output( "\n" );
1088 * Handle some last-minute setup here.
1090 public function finalSetup() {
1091 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1092 global $wgDBadminuser, $wgDBadminpassword;
1093 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1095 # Turn off output buffering again, it might have been turned on in the settings files
1096 if ( ob_get_level() ) {
1100 $wgCommandLineMode = true;
1102 # Override $wgServer
1103 if ( $this->hasOption( 'server' ) ) {
1104 $wgServer = $this->getOption( 'server', $wgServer );
1107 # If these were passed, use them
1108 if ( $this->mDbUser
) {
1109 $wgDBadminuser = $this->mDbUser
;
1111 if ( $this->mDbPass
) {
1112 $wgDBadminpassword = $this->mDbPass
;
1115 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1116 $wgDBuser = $wgDBadminuser;
1117 $wgDBpassword = $wgDBadminpassword;
1119 if ( $wgDBservers ) {
1121 * @var $wgDBservers array
1123 foreach ( $wgDBservers as $i => $server ) {
1124 $wgDBservers[$i]['user'] = $wgDBuser;
1125 $wgDBservers[$i]['password'] = $wgDBpassword;
1128 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1129 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1130 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1132 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1135 // Per-script profiling; useful for debugging
1136 $this->activateProfiler();
1138 $this->afterFinalSetup();
1140 $wgShowSQLErrors = true;
1142 MediaWiki\
suppressWarnings();
1143 set_time_limit( 0 );
1144 MediaWiki\restoreWarnings
();
1146 $this->adjustMemoryLimit();
1150 * Execute a callback function at the end of initialisation
1152 protected function afterFinalSetup() {
1153 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1154 call_user_func( MW_CMDLINE_CALLBACK
);
1159 * Potentially debug globals. Originally a feature only
1162 public function globals() {
1163 if ( $this->hasOption( 'globals' ) ) {
1164 print_r( $GLOBALS );
1169 * Generic setup for most installs. Returns the location of LocalSettings
1172 public function loadSettings() {
1173 global $wgCommandLineMode, $IP;
1175 if ( isset( $this->mOptions
['conf'] ) ) {
1176 $settingsFile = $this->mOptions
['conf'];
1177 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1178 $settingsFile = MW_CONFIG_FILE
;
1180 $settingsFile = "$IP/LocalSettings.php";
1182 if ( isset( $this->mOptions
['wiki'] ) ) {
1183 $bits = explode( '-', $this->mOptions
['wiki'] );
1184 if ( count( $bits ) == 1 ) {
1187 define( 'MW_DB', $bits[0] );
1188 define( 'MW_PREFIX', $bits[1] );
1191 if ( !is_readable( $settingsFile ) ) {
1192 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1193 "must exist and be readable in the source directory.\n" .
1194 "Use --conf to specify it." );
1196 $wgCommandLineMode = true;
1198 return $settingsFile;
1202 * Support function for cleaning up redundant text records
1203 * @param bool $delete Whether or not to actually delete the records
1204 * @author Rob Church <robchur@gmail.com>
1206 public function purgeRedundantText( $delete = true ) {
1207 # Data should come off the master, wrapped in a transaction
1208 $dbw = $this->getDB( DB_MASTER
);
1209 $this->beginTransaction( $dbw, __METHOD__
);
1211 # Get "active" text records from the revisions table
1213 $this->output( 'Searching for active text records in revisions table...' );
1214 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1215 foreach ( $res as $row ) {
1216 $cur[] = $row->rev_text_id
;
1218 $this->output( "done.\n" );
1220 # Get "active" text records from the archive table
1221 $this->output( 'Searching for active text records in archive table...' );
1222 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1223 foreach ( $res as $row ) {
1224 # old pre-MW 1.5 records can have null ar_text_id's.
1225 if ( $row->ar_text_id
!== null ) {
1226 $cur[] = $row->ar_text_id
;
1229 $this->output( "done.\n" );
1231 # Get the IDs of all text records not in these sets
1232 $this->output( 'Searching for inactive text records...' );
1233 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1234 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1236 foreach ( $res as $row ) {
1237 $old[] = $row->old_id
;
1239 $this->output( "done.\n" );
1241 # Inform the user of what we're going to do
1242 $count = count( $old );
1243 $this->output( "$count inactive items found.\n" );
1245 # Delete as appropriate
1246 if ( $delete && $count ) {
1247 $this->output( 'Deleting...' );
1248 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1249 $this->output( "done.\n" );
1253 $this->commitTransaction( $dbw, __METHOD__
);
1257 * Get the maintenance directory.
1260 protected function getDir() {
1265 * Returns a database to be used by current maintenance script. It can be set by setDB().
1266 * If not set, wfGetDB() will be used.
1267 * This function has the same parameters as wfGetDB()
1269 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1270 * @param array $groups default: empty array
1271 * @param string|bool $wiki default: current wiki
1272 * @return IMaintainableDatabase
1274 protected function getDB( $db, $groups = [], $wiki = false ) {
1275 if ( is_null( $this->mDb
) ) {
1276 return wfGetDB( $db, $groups, $wiki );
1283 * Sets database object to be returned by getDB().
1285 * @param IDatabase $db
1287 public function setDB( IDatabase
$db ) {
1292 * Begin a transcation on a DB
1294 * This method makes it clear that begin() is called from a maintenance script,
1295 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1297 * @param IDatabase $dbw
1298 * @param string $fname Caller name
1301 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1302 $dbw->begin( $fname );
1306 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1308 * This method makes it clear that commit() is called from a maintenance script,
1309 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1311 * @param IDatabase $dbw
1312 * @param string $fname Caller name
1313 * @return bool Whether the replica DB wait succeeded
1316 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1317 $dbw->commit( $fname );
1319 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1320 $lbFactory->waitForReplication(
1321 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1323 $this->lastReplicationWait
= microtime( true );
1326 } catch ( DBReplicationWaitError
$e ) {
1332 * Rollback the transcation on a DB handle
1334 * This method makes it clear that rollback() is called from a maintenance script,
1335 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1337 * @param IDatabase $dbw
1338 * @param string $fname Caller name
1341 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1342 $dbw->rollback( $fname );
1346 * Lock the search index
1347 * @param IMaintainableDatabase &$db
1349 private function lockSearchindex( $db ) {
1350 $write = [ 'searchindex' ];
1360 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1365 * @param IMaintainableDatabase &$db
1367 private function unlockSearchindex( $db ) {
1368 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1372 * Unlock and lock again
1373 * Since the lock is low-priority, queued reads will be able to complete
1374 * @param IMaintainableDatabase &$db
1376 private function relockSearchindex( $db ) {
1377 $this->unlockSearchindex( $db );
1378 $this->lockSearchindex( $db );
1382 * Perform a search index update with locking
1383 * @param int $maxLockTime The maximum time to keep the search index locked.
1384 * @param string $callback The function that will update the function.
1385 * @param IMaintainableDatabase $dbw
1386 * @param array $results
1388 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1392 if ( $maxLockTime ) {
1393 $this->output( " --- Waiting for lock ---" );
1394 $this->lockSearchindex( $dbw );
1396 $this->output( "\n" );
1399 # Loop through the results and do a search update
1400 foreach ( $results as $row ) {
1401 # Allow reads to be processed
1402 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1403 $this->output( " --- Relocking ---" );
1404 $this->relockSearchindex( $dbw );
1406 $this->output( "\n" );
1408 call_user_func( $callback, $dbw, $row );
1411 # Unlock searchindex
1412 if ( $maxLockTime ) {
1413 $this->output( " --- Unlocking --" );
1414 $this->unlockSearchindex( $dbw );
1415 $this->output( "\n" );
1420 * Update the searchindex table for a given pageid
1421 * @param IDatabase $dbw A database write handle
1422 * @param int $pageId The page ID to update.
1423 * @return null|string
1425 public function updateSearchIndexForPage( $dbw, $pageId ) {
1426 // Get current revision
1427 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1430 $titleObj = $rev->getTitle();
1431 $title = $titleObj->getPrefixedDBkey();
1432 $this->output( "$title..." );
1433 # Update searchindex
1434 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1436 $this->output( "\n" );
1443 * Count down from $seconds to zero on the terminal, with a one-second pause
1444 * between showing each number. If the maintenance script is in quiet mode,
1445 * this function does nothing.
1449 * @codeCoverageIgnore
1450 * @param int $seconds
1452 protected function countDown( $seconds ) {
1453 if ( $this->isQuiet() ) {
1456 for ( $i = $seconds; $i >= 0; $i-- ) {
1457 if ( $i != $seconds ) {
1458 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1460 $this->output( $i );
1465 $this->output( "\n" );
1469 * Wrapper for posix_isatty()
1470 * We default as considering stdin a tty (for nice readline methods)
1471 * but treating stout as not a tty to avoid color codes
1473 * @param mixed $fd File descriptor
1476 public static function posix_isatty( $fd ) {
1477 if ( !function_exists( 'posix_isatty' ) ) {
1480 return posix_isatty( $fd );
1485 * Prompt the console for input
1486 * @param string $prompt What to begin the line with, like '> '
1487 * @return string Response
1489 public static function readconsole( $prompt = '> ' ) {
1490 static $isatty = null;
1491 if ( is_null( $isatty ) ) {
1492 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1495 if ( $isatty && function_exists( 'readline' ) ) {
1496 return readline( $prompt );
1499 $st = self
::readlineEmulation( $prompt );
1501 if ( feof( STDIN
) ) {
1504 $st = fgets( STDIN
, 1024 );
1507 if ( $st === false ) {
1510 $resp = trim( $st );
1517 * Emulate readline()
1518 * @param string $prompt What to begin the line with, like '> '
1521 private static function readlineEmulation( $prompt ) {
1522 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1523 if ( !wfIsWindows() && $bash ) {
1525 $encPrompt = wfEscapeShellArg( $prompt );
1526 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1527 $encCommand = wfEscapeShellArg( $command );
1528 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1530 if ( $retval == 0 ) {
1532 } elseif ( $retval == 127 ) {
1533 // Couldn't execute bash even though we thought we saw it.
1534 // Shell probably spit out an error message, sorry :(
1535 // Fall through to fgets()...
1542 // Fallback... we'll have no editing controls, EWWW
1543 if ( feof( STDIN
) ) {
1548 return fgets( STDIN
, 1024 );
1552 * Get the terminal size as a two-element array where the first element
1553 * is the width (number of columns) and the second element is the height
1558 public static function getTermSize() {
1559 $default = [ 80, 50 ];
1560 if ( wfIsWindows() ) {
1563 // It's possible to get the screen size with VT-100 terminal escapes,
1564 // but reading the responses is not possible without setting raw mode
1565 // (unless you want to require the user to press enter), and that
1566 // requires an ioctl(), which we can't do. So we have to shell out to
1567 // something that can do the relevant syscalls. There are a few
1568 // options. Linux and Mac OS X both have "stty size" which does the
1571 $size = wfShellExec( 'stty size', $retval );
1572 if ( $retval !== 0 ) {
1575 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1578 return [ intval( $m[2] ), intval( $m[1] ) ];
1582 * Call this to set up the autoloader to allow classes to be used from the
1585 public static function requireTestsAutoloader() {
1586 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1591 * Fake maintenance wrapper, mostly used for the web installer/updater
1593 class FakeMaintenance
extends Maintenance
{
1594 protected $mSelf = "FakeMaintenanceScript";
1596 public function execute() {
1602 * Class for scripts that perform database maintenance and want to log the
1603 * update in `updatelog` so we can later skip it
1605 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1606 public function __construct() {
1607 parent
::__construct();
1608 $this->addOption( 'force', 'Run the update even if it was completed already' );
1609 $this->setBatchSize( 200 );
1612 public function execute() {
1613 $db = $this->getDB( DB_MASTER
);
1614 $key = $this->getUpdateKey();
1616 if ( !$this->hasOption( 'force' )
1617 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1619 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1624 if ( !$this->doDBUpdates() ) {
1628 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1631 $this->output( $this->updatelogFailedMessage() . "\n" );
1638 * Message to show that the update was done already and was just skipped
1641 protected function updateSkippedMessage() {
1642 $key = $this->getUpdateKey();
1644 return "Update '{$key}' already logged as completed.";
1648 * Message to show that the update log was unable to log the completion of this update
1651 protected function updatelogFailedMessage() {
1652 $key = $this->getUpdateKey();
1654 return "Unable to log update '{$key}' as completed.";
1658 * Do the actual work. All child classes will need to implement this.
1659 * Return true to log the update as done or false (usually on failure).
1662 abstract protected function doDBUpdates();
1665 * Get the update key name to go in the update log table
1668 abstract protected function getUpdateKey();