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'] !== self
::class ||
$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 // This is sometimes called very early, before Setup.php is included.
385 if ( class_exists( MediaWikiServices
::class ) ) {
386 // Try to periodically flush buffered metrics to avoid OOMs
387 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
388 if ( $stats->getDataCount() > 1000 ) {
389 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
393 if ( $this->mQuiet
) {
396 if ( $channel === null ) {
397 $this->cleanupChanneled();
400 $out = preg_replace( '/\n\z/', '', $out );
401 $this->outputChanneled( $out, $channel );
406 * Throw an error to the user. Doesn't respect --quiet, so don't use
407 * this for non-error output
408 * @param string $err The error to display
409 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
411 protected function error( $err, $die = 0 ) {
412 if ( intval( $die ) !== 0 ) {
413 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
414 $this->fatalError( $err, intval( $die ) );
416 $this->outputChanneled( false );
417 if ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) {
418 fwrite( STDERR
, $err . "\n" );
425 * Output a message and terminate the current script.
427 * @param string $msg Error message
428 * @param int $exitCode PHP exit status. Should be in range 1-254.
431 protected function fatalError( $msg, $exitCode = 1 ) {
432 $this->error( $msg );
436 private $atLineStart = true;
437 private $lastChannel = null;
440 * Clean up channeled output. Output a newline if necessary.
442 public function cleanupChanneled() {
443 if ( !$this->atLineStart
) {
445 $this->atLineStart
= true;
450 * Message outputter with channeled message support. Messages on the
451 * same channel are concatenated, but any intervening messages in another
452 * channel start a new line.
453 * @param string $msg The message without trailing newline
454 * @param string $channel Channel identifier or null for no
455 * channel. Channel comparison uses ===.
457 public function outputChanneled( $msg, $channel = null ) {
458 if ( $msg === false ) {
459 $this->cleanupChanneled();
464 // End the current line if necessary
465 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
471 $this->atLineStart
= false;
472 if ( $channel === null ) {
473 // For unchanneled messages, output trailing newline immediately
475 $this->atLineStart
= true;
477 $this->lastChannel
= $channel;
481 * Does the script need different DB access? By default, we give Maintenance
482 * scripts normal rights to the DB. Sometimes, a script needs admin rights
483 * access for a reason and sometimes they want no access. Subclasses should
484 * override and return one of the following values, as needed:
485 * Maintenance::DB_NONE - For no DB access at all
486 * Maintenance::DB_STD - For normal DB access, default
487 * Maintenance::DB_ADMIN - For admin DB access
490 public function getDbType() {
495 * Add the default parameters to the scripts
497 protected function addDefaultParams() {
498 # Generic (non script dependant) options:
500 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
501 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
502 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
503 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
504 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
507 'Set a specific memory limit for the script, '
508 . '"max" for no limit or "default" to avoid changing it'
510 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
511 "http://en.wikipedia.org. This is sometimes necessary because " .
512 "server name detection may fail in command line scripts.", false, true );
513 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
515 # Save generic options to display them separately in help
516 $this->mGenericParameters
= $this->mParams
;
518 # Script dependant options:
520 // If we support a DB, show the options
521 if ( $this->getDbType() > 0 ) {
522 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
523 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
526 # Save additional script dependant options to display
527 # Â them separately in help
528 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
535 public function getConfig() {
536 if ( $this->config
=== null ) {
537 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
540 return $this->config
;
545 * @param Config $config
547 public function setConfig( Config
$config ) {
548 $this->config
= $config;
552 * Indicate that the specified extension must be
553 * loaded before the script can run.
555 * This *must* be called in the constructor.
558 * @param string $name
560 protected function requireExtension( $name ) {
561 $this->requiredExtensions
[] = $name;
565 * Verify that the required extensions are installed
569 public function checkRequiredExtensions() {
570 $registry = ExtensionRegistry
::getInstance();
572 foreach ( $this->requiredExtensions
as $name ) {
573 if ( !$registry->isLoaded( $name ) ) {
579 $joined = implode( ', ', $missing );
580 $msg = "The following extensions are required to be installed "
581 . "for this script to run: $joined. Please enable them and then try again.";
582 $this->fatalError( $msg );
587 * Set triggers like when to try to run deferred updates
590 public function setAgentAndTriggers() {
591 if ( function_exists( 'posix_getpwuid' ) ) {
592 $agent = posix_getpwuid( posix_geteuid() )['name'];
596 $agent .= '@' . wfHostname();
598 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
599 // Add a comment for easy SHOW PROCESSLIST interpretation
600 $lbFactory->setAgentName(
601 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
603 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
607 * @param LBFactory $LBFactory
608 * @param Config $config
611 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
612 $services = MediaWikiServices
::getInstance();
613 $stats = $services->getStatsdDataFactory();
614 // Hook into period lag checks which often happen in long-running scripts
615 $lbFactory = $services->getDBLoadBalancerFactory();
616 $lbFactory->setWaitForReplicationListener(
618 function () use ( $stats, $config ) {
619 // Check config in case of JobRunner and unit tests
620 if ( $config->get( 'CommandLineMode' ) ) {
621 DeferredUpdates
::tryOpportunisticExecute( 'run' );
623 // Try to periodically flush buffered metrics to avoid OOMs
624 MediaWiki
::emitBufferedStatsdData( $stats, $config );
627 // Check for other windows to run them. A script may read or do a few writes
628 // to the master but mostly be writing to something else, like a file store.
629 $lbFactory->getMainLB()->setTransactionListener(
631 function ( $trigger ) use ( $stats, $config ) {
632 // Check config in case of JobRunner and unit tests
633 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
634 DeferredUpdates
::tryOpportunisticExecute( 'run' );
636 // Try to periodically flush buffered metrics to avoid OOMs
637 MediaWiki
::emitBufferedStatsdData( $stats, $config );
643 * Run a child maintenance script. Pass all of the current arguments
645 * @param string $maintClass A name of a child maintenance class
646 * @param string $classFile Full path of where the child is
647 * @return Maintenance
649 public function runChild( $maintClass, $classFile = null ) {
650 // Make sure the class is loaded first
651 if ( !class_exists( $maintClass ) ) {
653 require_once $classFile;
655 if ( !class_exists( $maintClass ) ) {
656 $this->error( "Cannot spawn child: $maintClass" );
661 * @var $child Maintenance
663 $child = new $maintClass();
664 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
665 if ( !is_null( $this->mDb
) ) {
666 $child->setDB( $this->mDb
);
673 * Do some sanity checking and basic setup
675 public function setup() {
676 global $IP, $wgCommandLineMode, $wgRequestTime;
678 # Abort if called from a web server
679 # wfIsCLI() is not available yet
680 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
681 $this->fatalError( 'This script must be run from the command line' );
684 if ( $IP === null ) {
685 $this->fatalError( "\$IP not set, aborting!\n" .
686 '(Did you forget to call parent::__construct() in your maintenance script?)' );
689 # Make sure we can handle script parameters
690 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
691 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
694 // Send PHP warnings and errors to stderr instead of stdout.
695 // This aids in diagnosing problems, while keeping messages
696 // out of redirected output.
697 if ( ini_get( 'display_errors' ) ) {
698 ini_set( 'display_errors', 'stderr' );
701 $this->loadParamsAndArgs();
704 # Set the memory limit
705 # Note we need to set it again later in cache LocalSettings changed it
706 $this->adjustMemoryLimit();
708 # Set max execution time to 0 (no limit). PHP.net says that
709 # "When running PHP from the command line the default setting is 0."
710 # But sometimes this doesn't seem to be the case.
711 ini_set( 'max_execution_time', 0 );
713 $wgRequestTime = microtime( true );
715 # Define us as being in MediaWiki
716 define( 'MEDIAWIKI', true );
718 $wgCommandLineMode = true;
720 # Turn off output buffering if it's on
721 while ( ob_get_level() > 0 ) {
725 $this->validateParamsAndArgs();
729 * Normally we disable the memory_limit when running admin scripts.
730 * Some scripts may wish to actually set a limit, however, to avoid
731 * blowing up unexpectedly. We also support a --memory-limit option,
732 * to allow sysadmins to explicitly set one if they'd prefer to override
733 * defaults (or for people using Suhosin which yells at you for trying
734 * to disable the limits)
737 public function memoryLimit() {
738 $limit = $this->getOption( 'memory-limit', 'max' );
739 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
744 * Adjusts PHP's memory limit to better suit our needs, if needed.
746 protected function adjustMemoryLimit() {
747 $limit = $this->memoryLimit();
748 if ( $limit == 'max' ) {
749 $limit = -1; // no memory limit
751 if ( $limit != 'default' ) {
752 ini_set( 'memory_limit', $limit );
757 * Activate the profiler (assuming $wgProfiler is set)
759 protected function activateProfiler() {
760 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
762 $output = $this->getOption( 'profiler' );
767 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
768 $class = $wgProfiler['class'];
769 /** @var Profiler $profiler */
770 $profiler = new $class(
771 [ 'sampling' => 1, 'output' => [ $output ] ]
773 +
[ 'threshold' => $wgProfileLimit ]
775 $profiler->setTemplated( true );
776 Profiler
::replaceStubInstance( $profiler );
779 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
780 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
781 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
785 * Clear all params and arguments.
787 public function clearParamsAndArgs() {
788 $this->mOptions
= [];
790 $this->mInputLoaded
= false;
794 * Load params and arguments from a given array
795 * of command-line arguments
800 public function loadWithArgv( $argv ) {
803 $this->orderedOptions
= [];
806 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
807 if ( $arg == '--' ) {
808 # End of options, remainder should be considered arguments
809 $arg = next( $argv );
810 while ( $arg !== false ) {
812 $arg = next( $argv );
815 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
817 $option = substr( $arg, 2 );
818 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
819 $param = next( $argv );
820 if ( $param === false ) {
821 $this->error( "\nERROR: $option parameter needs a value after it\n" );
822 $this->maybeHelp( true );
825 $this->setParam( $options, $option, $param );
827 $bits = explode( '=', $option, 2 );
828 if ( count( $bits ) > 1 ) {
835 $this->setParam( $options, $option, $param );
837 } elseif ( $arg == '-' ) {
838 # Lonely "-", often used to indicate stdin or stdout.
840 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
842 $argLength = strlen( $arg );
843 for ( $p = 1; $p < $argLength; $p++
) {
845 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
846 $option = $this->mShortParamsMap
[$option];
849 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
850 $param = next( $argv );
851 if ( $param === false ) {
852 $this->error( "\nERROR: $option parameter needs a value after it\n" );
853 $this->maybeHelp( true );
855 $this->setParam( $options, $option, $param );
857 $this->setParam( $options, $option, 1 );
865 $this->mOptions
= $options;
866 $this->mArgs
= $args;
867 $this->loadSpecialVars();
868 $this->mInputLoaded
= true;
872 * Helper function used solely by loadParamsAndArgs
873 * to prevent code duplication
875 * This sets the param in the options array based on
876 * whether or not it can be specified multiple times.
879 * @param array $options
880 * @param string $option
881 * @param mixed $value
883 private function setParam( &$options, $option, $value ) {
884 $this->orderedOptions
[] = [ $option, $value ];
886 if ( isset( $this->mParams
[$option] ) ) {
887 $multi = $this->mParams
[$option]['multiOccurrence'];
891 $exists = array_key_exists( $option, $options );
892 if ( $multi && $exists ) {
893 $options[$option][] = $value;
894 } elseif ( $multi ) {
895 $options[$option] = [ $value ];
896 } elseif ( !$exists ) {
897 $options[$option] = $value;
899 $this->error( "\nERROR: $option parameter given twice\n" );
900 $this->maybeHelp( true );
905 * Process command line arguments
906 * $mOptions becomes an array with keys set to the option names
907 * $mArgs becomes a zero-based array containing the non-option arguments
909 * @param string $self The name of the script, if any
910 * @param array $opts An array of options, in form of key=>value
911 * @param array $args An array of command line arguments
913 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
914 # If we were given opts or args, set those and return early
916 $this->mSelf
= $self;
917 $this->mInputLoaded
= true;
920 $this->mOptions
= $opts;
921 $this->mInputLoaded
= true;
924 $this->mArgs
= $args;
925 $this->mInputLoaded
= true;
928 # If we've already loaded input (either by user values or from $argv)
929 # skip on loading it again. The array_shift() will corrupt values if
930 # it's run again and again
931 if ( $this->mInputLoaded
) {
932 $this->loadSpecialVars();
938 $this->mSelf
= $argv[0];
939 $this->loadWithArgv( array_slice( $argv, 1 ) );
943 * Run some validation checks on the params, etc
945 protected function validateParamsAndArgs() {
947 # Check to make sure we've got all the required options
948 foreach ( $this->mParams
as $opt => $info ) {
949 if ( $info['require'] && !$this->hasOption( $opt ) ) {
950 $this->error( "Param $opt required!" );
955 foreach ( $this->mArgList
as $k => $info ) {
956 if ( $info['require'] && !$this->hasArg( $k ) ) {
957 $this->error( 'Argument <' . $info['name'] . '> required!' );
963 $this->maybeHelp( true );
968 * Handle the special variables that are global to all scripts
970 protected function loadSpecialVars() {
971 if ( $this->hasOption( 'dbuser' ) ) {
972 $this->mDbUser
= $this->getOption( 'dbuser' );
974 if ( $this->hasOption( 'dbpass' ) ) {
975 $this->mDbPass
= $this->getOption( 'dbpass' );
977 if ( $this->hasOption( 'quiet' ) ) {
978 $this->mQuiet
= true;
980 if ( $this->hasOption( 'batch-size' ) ) {
981 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
986 * Maybe show the help.
987 * @param bool $force Whether to force the help to show, default false
989 protected function maybeHelp( $force = false ) {
990 if ( !$force && !$this->hasOption( 'help' ) ) {
994 $screenWidth = 80; // TODO: Calculate this!
996 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
998 ksort( $this->mParams
);
999 $this->mQuiet
= false;
1002 if ( $this->mDescription
) {
1003 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1005 $output = "\nUsage: php " . basename( $this->mSelf
);
1007 // ... append parameters ...
1008 if ( $this->mParams
) {
1009 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
1012 // ... and append arguments.
1013 if ( $this->mArgList
) {
1015 foreach ( $this->mArgList
as $k => $arg ) {
1016 if ( $arg['require'] ) {
1017 $output .= '<' . $arg['name'] . '>';
1019 $output .= '[' . $arg['name'] . ']';
1021 if ( $k < count( $this->mArgList
) - 1 ) {
1026 $this->output( "$output\n\n" );
1028 # TODO abstract some repetitive code below
1030 // Generic parameters
1031 $this->output( "Generic maintenance parameters:\n" );
1032 foreach ( $this->mGenericParameters
as $par => $info ) {
1033 if ( $info['shortName'] !== false ) {
1034 $par .= " (-{$info['shortName']})";
1037 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1038 "\n$tab$tab" ) . "\n"
1041 $this->output( "\n" );
1043 $scriptDependantParams = $this->mDependantParameters
;
1044 if ( count( $scriptDependantParams ) > 0 ) {
1045 $this->output( "Script dependant parameters:\n" );
1046 // Parameters description
1047 foreach ( $scriptDependantParams as $par => $info ) {
1048 if ( $info['shortName'] !== false ) {
1049 $par .= " (-{$info['shortName']})";
1052 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1053 "\n$tab$tab" ) . "\n"
1056 $this->output( "\n" );
1059 // Script specific parameters not defined on construction by
1060 // Maintenance::addDefaultParams()
1061 $scriptSpecificParams = array_diff_key(
1062 # all script parameters:
1064 # remove the Maintenance default parameters:
1065 $this->mGenericParameters
,
1066 $this->mDependantParameters
1068 if ( count( $scriptSpecificParams ) > 0 ) {
1069 $this->output( "Script specific parameters:\n" );
1070 // Parameters description
1071 foreach ( $scriptSpecificParams as $par => $info ) {
1072 if ( $info['shortName'] !== false ) {
1073 $par .= " (-{$info['shortName']})";
1076 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1077 "\n$tab$tab" ) . "\n"
1080 $this->output( "\n" );
1084 if ( count( $this->mArgList
) > 0 ) {
1085 $this->output( "Arguments:\n" );
1086 // Arguments description
1087 foreach ( $this->mArgList
as $info ) {
1088 $openChar = $info['require'] ?
'<' : '[';
1089 $closeChar = $info['require'] ?
'>' : ']';
1091 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1092 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1095 $this->output( "\n" );
1102 * Handle some last-minute setup here.
1104 public function finalSetup() {
1105 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1106 global $wgDBadminuser, $wgDBadminpassword;
1107 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1109 # Turn off output buffering again, it might have been turned on in the settings files
1110 if ( ob_get_level() ) {
1114 $wgCommandLineMode = true;
1116 # Override $wgServer
1117 if ( $this->hasOption( 'server' ) ) {
1118 $wgServer = $this->getOption( 'server', $wgServer );
1121 # If these were passed, use them
1122 if ( $this->mDbUser
) {
1123 $wgDBadminuser = $this->mDbUser
;
1125 if ( $this->mDbPass
) {
1126 $wgDBadminpassword = $this->mDbPass
;
1129 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1130 $wgDBuser = $wgDBadminuser;
1131 $wgDBpassword = $wgDBadminpassword;
1133 if ( $wgDBservers ) {
1135 * @var $wgDBservers array
1137 foreach ( $wgDBservers as $i => $server ) {
1138 $wgDBservers[$i]['user'] = $wgDBuser;
1139 $wgDBservers[$i]['password'] = $wgDBpassword;
1142 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1143 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1144 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1146 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1149 // Per-script profiling; useful for debugging
1150 $this->activateProfiler();
1152 $this->afterFinalSetup();
1154 $wgShowSQLErrors = true;
1156 MediaWiki\
suppressWarnings();
1157 set_time_limit( 0 );
1158 MediaWiki\restoreWarnings
();
1160 $this->adjustMemoryLimit();
1164 * Execute a callback function at the end of initialisation
1166 protected function afterFinalSetup() {
1167 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1168 call_user_func( MW_CMDLINE_CALLBACK
);
1173 * Potentially debug globals. Originally a feature only
1176 public function globals() {
1177 if ( $this->hasOption( 'globals' ) ) {
1178 print_r( $GLOBALS );
1183 * Generic setup for most installs. Returns the location of LocalSettings
1186 public function loadSettings() {
1187 global $wgCommandLineMode, $IP;
1189 if ( isset( $this->mOptions
['conf'] ) ) {
1190 $settingsFile = $this->mOptions
['conf'];
1191 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1192 $settingsFile = MW_CONFIG_FILE
;
1194 $settingsFile = "$IP/LocalSettings.php";
1196 if ( isset( $this->mOptions
['wiki'] ) ) {
1197 $bits = explode( '-', $this->mOptions
['wiki'] );
1198 if ( count( $bits ) == 1 ) {
1201 define( 'MW_DB', $bits[0] );
1202 define( 'MW_PREFIX', $bits[1] );
1205 if ( !is_readable( $settingsFile ) ) {
1206 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1207 "must exist and be readable in the source directory.\n" .
1208 "Use --conf to specify it." );
1210 $wgCommandLineMode = true;
1212 return $settingsFile;
1216 * Support function for cleaning up redundant text records
1217 * @param bool $delete Whether or not to actually delete the records
1218 * @author Rob Church <robchur@gmail.com>
1220 public function purgeRedundantText( $delete = true ) {
1221 # Data should come off the master, wrapped in a transaction
1222 $dbw = $this->getDB( DB_MASTER
);
1223 $this->beginTransaction( $dbw, __METHOD__
);
1225 # Get "active" text records from the revisions table
1227 $this->output( 'Searching for active text records in revisions table...' );
1228 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1229 foreach ( $res as $row ) {
1230 $cur[] = $row->rev_text_id
;
1232 $this->output( "done.\n" );
1234 # Get "active" text records from the archive table
1235 $this->output( 'Searching for active text records in archive table...' );
1236 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1237 foreach ( $res as $row ) {
1238 # old pre-MW 1.5 records can have null ar_text_id's.
1239 if ( $row->ar_text_id
!== null ) {
1240 $cur[] = $row->ar_text_id
;
1243 $this->output( "done.\n" );
1245 # Get the IDs of all text records not in these sets
1246 $this->output( 'Searching for inactive text records...' );
1247 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1248 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1250 foreach ( $res as $row ) {
1251 $old[] = $row->old_id
;
1253 $this->output( "done.\n" );
1255 # Inform the user of what we're going to do
1256 $count = count( $old );
1257 $this->output( "$count inactive items found.\n" );
1259 # Delete as appropriate
1260 if ( $delete && $count ) {
1261 $this->output( 'Deleting...' );
1262 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1263 $this->output( "done.\n" );
1267 $this->commitTransaction( $dbw, __METHOD__
);
1271 * Get the maintenance directory.
1274 protected function getDir() {
1279 * Returns a database to be used by current maintenance script. It can be set by setDB().
1280 * If not set, wfGetDB() will be used.
1281 * This function has the same parameters as wfGetDB()
1283 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1284 * @param array $groups default: empty array
1285 * @param string|bool $wiki default: current wiki
1286 * @return IMaintainableDatabase
1288 protected function getDB( $db, $groups = [], $wiki = false ) {
1289 if ( is_null( $this->mDb
) ) {
1290 return wfGetDB( $db, $groups, $wiki );
1297 * Sets database object to be returned by getDB().
1299 * @param IDatabase $db
1301 public function setDB( IDatabase
$db ) {
1306 * Begin a transcation on a DB
1308 * This method makes it clear that begin() is called from a maintenance script,
1309 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1311 * @param IDatabase $dbw
1312 * @param string $fname Caller name
1315 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1316 $dbw->begin( $fname );
1320 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1322 * This method makes it clear that commit() is called from a maintenance script,
1323 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1325 * @param IDatabase $dbw
1326 * @param string $fname Caller name
1327 * @return bool Whether the replica DB wait succeeded
1330 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1331 $dbw->commit( $fname );
1333 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1334 $lbFactory->waitForReplication(
1335 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1337 $this->lastReplicationWait
= microtime( true );
1340 } catch ( DBReplicationWaitError
$e ) {
1346 * Rollback the transcation on a DB handle
1348 * This method makes it clear that rollback() is called from a maintenance script,
1349 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1351 * @param IDatabase $dbw
1352 * @param string $fname Caller name
1355 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1356 $dbw->rollback( $fname );
1360 * Lock the search index
1361 * @param IMaintainableDatabase &$db
1363 private function lockSearchindex( $db ) {
1364 $write = [ 'searchindex' ];
1374 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1379 * @param IMaintainableDatabase &$db
1381 private function unlockSearchindex( $db ) {
1382 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1386 * Unlock and lock again
1387 * Since the lock is low-priority, queued reads will be able to complete
1388 * @param IMaintainableDatabase &$db
1390 private function relockSearchindex( $db ) {
1391 $this->unlockSearchindex( $db );
1392 $this->lockSearchindex( $db );
1396 * Perform a search index update with locking
1397 * @param int $maxLockTime The maximum time to keep the search index locked.
1398 * @param string $callback The function that will update the function.
1399 * @param IMaintainableDatabase $dbw
1400 * @param array $results
1402 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1406 if ( $maxLockTime ) {
1407 $this->output( " --- Waiting for lock ---" );
1408 $this->lockSearchindex( $dbw );
1410 $this->output( "\n" );
1413 # Loop through the results and do a search update
1414 foreach ( $results as $row ) {
1415 # Allow reads to be processed
1416 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1417 $this->output( " --- Relocking ---" );
1418 $this->relockSearchindex( $dbw );
1420 $this->output( "\n" );
1422 call_user_func( $callback, $dbw, $row );
1425 # Unlock searchindex
1426 if ( $maxLockTime ) {
1427 $this->output( " --- Unlocking --" );
1428 $this->unlockSearchindex( $dbw );
1429 $this->output( "\n" );
1434 * Update the searchindex table for a given pageid
1435 * @param IDatabase $dbw A database write handle
1436 * @param int $pageId The page ID to update.
1437 * @return null|string
1439 public function updateSearchIndexForPage( $dbw, $pageId ) {
1440 // Get current revision
1441 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1444 $titleObj = $rev->getTitle();
1445 $title = $titleObj->getPrefixedDBkey();
1446 $this->output( "$title..." );
1447 # Update searchindex
1448 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1450 $this->output( "\n" );
1457 * Count down from $seconds to zero on the terminal, with a one-second pause
1458 * between showing each number. If the maintenance script is in quiet mode,
1459 * this function does nothing.
1463 * @codeCoverageIgnore
1464 * @param int $seconds
1466 protected function countDown( $seconds ) {
1467 if ( $this->isQuiet() ) {
1470 for ( $i = $seconds; $i >= 0; $i-- ) {
1471 if ( $i != $seconds ) {
1472 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1474 $this->output( $i );
1479 $this->output( "\n" );
1483 * Wrapper for posix_isatty()
1484 * We default as considering stdin a tty (for nice readline methods)
1485 * but treating stout as not a tty to avoid color codes
1487 * @param mixed $fd File descriptor
1490 public static function posix_isatty( $fd ) {
1491 if ( !function_exists( 'posix_isatty' ) ) {
1494 return posix_isatty( $fd );
1499 * Prompt the console for input
1500 * @param string $prompt What to begin the line with, like '> '
1501 * @return string Response
1503 public static function readconsole( $prompt = '> ' ) {
1504 static $isatty = null;
1505 if ( is_null( $isatty ) ) {
1506 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1509 if ( $isatty && function_exists( 'readline' ) ) {
1510 return readline( $prompt );
1513 $st = self
::readlineEmulation( $prompt );
1515 if ( feof( STDIN
) ) {
1518 $st = fgets( STDIN
, 1024 );
1521 if ( $st === false ) {
1524 $resp = trim( $st );
1531 * Emulate readline()
1532 * @param string $prompt What to begin the line with, like '> '
1535 private static function readlineEmulation( $prompt ) {
1536 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1537 if ( !wfIsWindows() && $bash ) {
1539 $encPrompt = wfEscapeShellArg( $prompt );
1540 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1541 $encCommand = wfEscapeShellArg( $command );
1542 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1544 if ( $retval == 0 ) {
1546 } elseif ( $retval == 127 ) {
1547 // Couldn't execute bash even though we thought we saw it.
1548 // Shell probably spit out an error message, sorry :(
1549 // Fall through to fgets()...
1556 // Fallback... we'll have no editing controls, EWWW
1557 if ( feof( STDIN
) ) {
1562 return fgets( STDIN
, 1024 );
1566 * Get the terminal size as a two-element array where the first element
1567 * is the width (number of columns) and the second element is the height
1572 public static function getTermSize() {
1573 $default = [ 80, 50 ];
1574 if ( wfIsWindows() ) {
1577 // It's possible to get the screen size with VT-100 terminal escapes,
1578 // but reading the responses is not possible without setting raw mode
1579 // (unless you want to require the user to press enter), and that
1580 // requires an ioctl(), which we can't do. So we have to shell out to
1581 // something that can do the relevant syscalls. There are a few
1582 // options. Linux and Mac OS X both have "stty size" which does the
1585 $size = wfShellExec( 'stty size', $retval );
1586 if ( $retval !== 0 ) {
1589 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1592 return [ intval( $m[2] ), intval( $m[1] ) ];
1596 * Call this to set up the autoloader to allow classes to be used from the
1599 public static function requireTestsAutoloader() {
1600 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1605 * Fake maintenance wrapper, mostly used for the web installer/updater
1607 class FakeMaintenance
extends Maintenance
{
1608 protected $mSelf = "FakeMaintenanceScript";
1610 public function execute() {
1616 * Class for scripts that perform database maintenance and want to log the
1617 * update in `updatelog` so we can later skip it
1619 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1620 public function __construct() {
1621 parent
::__construct();
1622 $this->addOption( 'force', 'Run the update even if it was completed already' );
1623 $this->setBatchSize( 200 );
1626 public function execute() {
1627 $db = $this->getDB( DB_MASTER
);
1628 $key = $this->getUpdateKey();
1630 if ( !$this->hasOption( 'force' )
1631 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1633 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1638 if ( !$this->doDBUpdates() ) {
1642 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1645 $this->output( $this->updatelogFailedMessage() . "\n" );
1652 * Message to show that the update was done already and was just skipped
1655 protected function updateSkippedMessage() {
1656 $key = $this->getUpdateKey();
1658 return "Update '{$key}' already logged as completed.";
1662 * Message to show that the update log was unable to log the completion of this update
1665 protected function updatelogFailedMessage() {
1666 $key = $this->getUpdateKey();
1668 return "Unable to log update '{$key}' as completed.";
1672 * Do the actual work. All child classes will need to implement this.
1673 * Return true to log the update as done or false (usually on failure).
1676 abstract protected function doDBUpdates();
1679 * Get the update key name to go in the update log table
1682 abstract protected function getUpdateKey();