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 define( MW_ENTRY_POINT
, 'cli' );
25 // Bail on old versions of PHP, or if composer has not been run yet to install
27 require_once __DIR__
. '/../includes/PHPVersionCheck.php';
28 wfEntryPointCheck( 'text' );
30 use MediaWiki\Shell\Shell
;
31 use Wikimedia\Rdbms\IResultWrapper
;
34 * @defgroup MaintenanceArchive Maintenance archives
35 * @ingroup Maintenance
38 // Define this so scripts can easily find doMaintenance.php
39 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
42 * @deprecated since 1.31
44 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
48 // Some extensions rely on MW_INSTALL_PATH to find core files to include. Setting it here helps them
49 // if they're included by a core script (like DatabaseUpdater) after Maintenance.php has already
51 if ( strval( getenv( 'MW_INSTALL_PATH' ) ) === '' ) {
52 putenv( 'MW_INSTALL_PATH=' . realpath( __DIR__
. '/..' ) );
55 use Wikimedia\Rdbms\IDatabase
;
56 use MediaWiki\Logger\LoggerFactory
;
57 use MediaWiki\MediaWikiServices
;
58 use Wikimedia\Rdbms\LBFactory
;
59 use Wikimedia\Rdbms\IMaintainableDatabase
;
62 * Abstract maintenance class for quickly writing and churning out
63 * maintenance scripts with minimal effort. All that _must_ be defined
64 * is the execute() method. See docs/maintenance.txt for more info
65 * and a quick demo of how to use it.
68 * params: registry of named values that may be passed to the script
69 * arg list: registry of positional values that may be passed to the script
70 * options: passed param values
71 * args: passed positional values
74 * mwscript somescript.php --foo=bar baz
76 * bar is the option value of the option for param foo
77 * baz is the arg value at index 0 in the arg list
80 * @ingroup Maintenance
82 abstract class Maintenance
{
84 * Constants for DB access type
85 * @see Maintenance::getDbType()
91 // Const for getStdin()
92 const STDIN_ALL
= 'all';
94 // Array of desired/allowed params
95 protected $mParams = [];
97 // Array of mapping short parameters to long ones
98 protected $mShortParamsMap = [];
100 // Array of desired/allowed args
101 protected $mArgList = [];
103 // This is the list of options that were actually passed
104 protected $mOptions = [];
106 // This is the list of arguments that were actually passed
107 protected $mArgs = [];
109 // Allow arbitrary options to be passed, or only specified ones?
110 protected $mAllowUnregisteredOptions = false;
112 // Name of the script currently running
115 // Special vars for params that are always used
116 protected $mQuiet = false;
117 protected $mDbUser, $mDbPass;
119 // A description of the script, children should change this via addDescription()
120 protected $mDescription = '';
122 // Have we already loaded our user input?
123 protected $mInputLoaded = false;
126 * Batch size. If a script supports this, they should set
127 * a default with setBatchSize()
131 protected $mBatchSize = null;
133 // Generic options added by addDefaultParams()
134 private $mGenericParameters = [];
135 // Generic options which might or not be supported by the script
136 private $mDependantParameters = [];
139 * Used by getDB() / setDB()
140 * @var IMaintainableDatabase
144 /** @var float UNIX timestamp */
145 private $lastReplicationWait = 0.0;
148 * Used when creating separate schema files.
154 * Accessible via getConfig()
161 * @see Maintenance::requireExtension
164 private $requiredExtensions = [];
167 * Used to read the options in the order they were passed.
168 * Useful for option chaining (Ex. dumpBackup.php). It will
169 * be an empty array if the options are passed in through
170 * loadParamsAndArgs( $self, $opts, $args ).
172 * This is an array of arrays where
173 * 0 => the option and 1 => parameter value.
177 public $orderedOptions = [];
180 * Default constructor. Children should call this *first* if implementing
181 * their own constructors
183 public function __construct() {
185 $IP = getenv( 'MW_INSTALL_PATH' );
187 $this->addDefaultParams();
188 register_shutdown_function( [ $this, 'outputChanneled' ], false );
192 * Should we execute the maintenance script, or just allow it to be included
193 * as a standalone class? It checks that the call stack only includes this
194 * function and "requires" (meaning was called from the file scope)
198 public static function shouldExecute() {
199 global $wgCommandLineMode;
201 if ( !function_exists( 'debug_backtrace' ) ) {
202 // If someone has a better idea...
203 return $wgCommandLineMode;
206 $bt = debug_backtrace();
207 $count = count( $bt );
209 return false; // sanity
211 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
212 return false; // last call should be to this function
214 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
215 for ( $i = 1; $i < $count; $i++
) {
216 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
217 return false; // previous calls should all be "requires"
225 * Do the actual work. All child classes will need to implement this
227 * @return bool|null|void True for success, false for failure. Not returning
228 * a value, or returning null, is also interpreted as success. Returning
229 * false for failure will cause doMaintenance.php to exit the process
230 * with a non-zero exit status.
232 abstract public function execute();
235 * Checks to see if a particular option in supported. Normally this means it
236 * has been registered by the script via addOption.
237 * @param string $name The name of the option
238 * @return bool true if the option exists, false otherwise
240 protected function supportsOption( $name ) {
241 return isset( $this->mParams
[$name] );
245 * Add a parameter to the script. Will be displayed on --help
246 * with the associated description
248 * @param string $name The name of the param (help, version, etc)
249 * @param string $description The description of the param to show on --help
250 * @param bool $required Is the param required?
251 * @param bool $withArg Is an argument required with this option?
252 * @param string|bool $shortName Character to use as short name
253 * @param bool $multiOccurrence Can this option be passed multiple times?
255 protected function addOption( $name, $description, $required = false,
256 $withArg = false, $shortName = false, $multiOccurrence = false
258 $this->mParams
[$name] = [
259 'desc' => $description,
260 'require' => $required,
261 'withArg' => $withArg,
262 'shortName' => $shortName,
263 'multiOccurrence' => $multiOccurrence
266 if ( $shortName !== false ) {
267 $this->mShortParamsMap
[$shortName] = $name;
272 * Checks to see if a particular option exists.
273 * @param string $name The name of the option
276 protected function hasOption( $name ) {
277 return isset( $this->mOptions
[$name] );
281 * Get an option, or return the default.
283 * If the option was added to support multiple occurrences,
284 * this will return an array.
286 * @param string $name The name of the param
287 * @param mixed|null $default Anything you want, default null
290 protected function getOption( $name, $default = null ) {
291 if ( $this->hasOption( $name ) ) {
292 return $this->mOptions
[$name];
294 // Set it so we don't have to provide the default again
295 $this->mOptions
[$name] = $default;
297 return $this->mOptions
[$name];
302 * Add some args that are needed
303 * @param string $arg Name of the arg, like 'start'
304 * @param string $description Short description of the arg
305 * @param bool $required Is this required?
307 protected function addArg( $arg, $description, $required = true ) {
308 $this->mArgList
[] = [
310 'desc' => $description,
311 'require' => $required
316 * Remove an option. Useful for removing options that won't be used in your script.
317 * @param string $name The option to remove.
319 protected function deleteOption( $name ) {
320 unset( $this->mParams
[$name] );
324 * Sets whether to allow unregistered options, which are options passed to
325 * a script that do not match an expected parameter.
326 * @param bool $allow Should we allow?
328 protected function setAllowUnregisteredOptions( $allow ) {
329 $this->mAllowUnregisteredOptions
= $allow;
333 * Set the description text.
334 * @param string $text The text of the description
336 protected function addDescription( $text ) {
337 $this->mDescription
= $text;
341 * Does a given argument exist?
342 * @param int $argId The integer value (from zero) for the arg
345 protected function hasArg( $argId = 0 ) {
346 if ( func_num_args() === 0 ) {
347 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
350 return isset( $this->mArgs
[$argId] );
355 * @param int $argId The integer value (from zero) for the arg
356 * @param mixed|null $default The default if it doesn't exist
359 protected function getArg( $argId = 0, $default = null ) {
360 if ( func_num_args() === 0 ) {
361 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
364 return $this->mArgs
[$argId] ??
$default;
374 protected function getBatchSize() {
375 return $this->mBatchSize
;
379 * Set the batch size.
380 * @param int $s The number of operations to do in a batch
382 protected function setBatchSize( $s = 0 ) {
383 $this->mBatchSize
= $s;
385 // If we support $mBatchSize, show the option.
386 // Used to be in addDefaultParams, but in order for that to
387 // work, subclasses would have to call this function in the constructor
388 // before they called parent::__construct which is just weird
389 // (and really wasn't done).
390 if ( $this->mBatchSize
) {
391 $this->addOption( 'batch-size', 'Run this many operations ' .
392 'per batch, default: ' . $this->mBatchSize
, false, true );
393 if ( isset( $this->mParams
['batch-size'] ) ) {
394 // This seems a little ugly...
395 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
401 * Get the script's name
404 public function getName() {
409 * Return input from stdin.
410 * @param int|null $len The number of bytes to read. If null, just return the handle.
411 * Maintenance::STDIN_ALL returns the full length
414 protected function getStdin( $len = null ) {
415 if ( $len == self
::STDIN_ALL
) {
416 return file_get_contents( 'php://stdin' );
418 $f = fopen( 'php://stdin', 'rt' );
422 $input = fgets( $f, $len );
425 return rtrim( $input );
431 public function isQuiet() {
432 return $this->mQuiet
;
436 * Throw some output to the user. Scripts can call this with no fears,
437 * as we handle all --quiet stuff here
438 * @param string $out The text to show to the user
439 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
441 protected function output( $out, $channel = null ) {
442 // This is sometimes called very early, before Setup.php is included.
443 if ( class_exists( MediaWikiServices
::class ) ) {
444 // Try to periodically flush buffered metrics to avoid OOMs
445 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
446 if ( $stats->getDataCount() > 1000 ) {
447 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
451 if ( $this->mQuiet
) {
454 if ( $channel === null ) {
455 $this->cleanupChanneled();
458 $out = preg_replace( '/\n\z/', '', $out );
459 $this->outputChanneled( $out, $channel );
464 * Throw an error to the user. Doesn't respect --quiet, so don't use
465 * this for non-error output
466 * @param string $err The error to display
467 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
469 protected function error( $err, $die = 0 ) {
470 if ( intval( $die ) !== 0 ) {
471 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
472 $this->fatalError( $err, intval( $die ) );
474 $this->outputChanneled( false );
476 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
477 !defined( 'MW_PHPUNIT_TEST' )
479 fwrite( STDERR
, $err . "\n" );
486 * Output a message and terminate the current script.
488 * @param string $msg Error message
489 * @param int $exitCode PHP exit status. Should be in range 1-254.
492 protected function fatalError( $msg, $exitCode = 1 ) {
493 $this->error( $msg );
497 private $atLineStart = true;
498 private $lastChannel = null;
501 * Clean up channeled output. Output a newline if necessary.
503 public function cleanupChanneled() {
504 if ( !$this->atLineStart
) {
506 $this->atLineStart
= true;
511 * Message outputter with channeled message support. Messages on the
512 * same channel are concatenated, but any intervening messages in another
513 * channel start a new line.
514 * @param string $msg The message without trailing newline
515 * @param string|null $channel Channel identifier or null for no
516 * channel. Channel comparison uses ===.
518 public function outputChanneled( $msg, $channel = null ) {
519 if ( $msg === false ) {
520 $this->cleanupChanneled();
525 // End the current line if necessary
526 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
532 $this->atLineStart
= false;
533 if ( $channel === null ) {
534 // For unchanneled messages, output trailing newline immediately
536 $this->atLineStart
= true;
538 $this->lastChannel
= $channel;
542 * Does the script need different DB access? By default, we give Maintenance
543 * scripts normal rights to the DB. Sometimes, a script needs admin rights
544 * access for a reason and sometimes they want no access. Subclasses should
545 * override and return one of the following values, as needed:
546 * Maintenance::DB_NONE - For no DB access at all
547 * Maintenance::DB_STD - For normal DB access, default
548 * Maintenance::DB_ADMIN - For admin DB access
551 public function getDbType() {
556 * Add the default parameters to the scripts
558 protected function addDefaultParams() {
559 # Generic (non script dependant) options:
561 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
562 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
563 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
564 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
565 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
568 'Set a specific memory limit for the script, '
569 . '"max" for no limit or "default" to avoid changing it',
573 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
574 "http://en.wikipedia.org. This is sometimes necessary because " .
575 "server name detection may fail in command line scripts.", false, true );
576 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
577 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
578 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
580 # Save generic options to display them separately in help
581 $this->mGenericParameters
= $this->mParams
;
583 # Script dependant options:
585 // If we support a DB, show the options
586 if ( $this->getDbType() > 0 ) {
587 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
588 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
589 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
592 # Save additional script dependant options to display
593 # Â them separately in help
594 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
601 public function getConfig() {
602 if ( $this->config
=== null ) {
603 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
606 return $this->config
;
611 * @param Config $config
613 public function setConfig( Config
$config ) {
614 $this->config
= $config;
618 * Indicate that the specified extension must be
619 * loaded before the script can run.
621 * This *must* be called in the constructor.
624 * @param string $name
626 protected function requireExtension( $name ) {
627 $this->requiredExtensions
[] = $name;
631 * Verify that the required extensions are installed
635 public function checkRequiredExtensions() {
636 $registry = ExtensionRegistry
::getInstance();
638 foreach ( $this->requiredExtensions
as $name ) {
639 if ( !$registry->isLoaded( $name ) ) {
645 $joined = implode( ', ', $missing );
646 $msg = "The following extensions are required to be installed "
647 . "for this script to run: $joined. Please enable them and then try again.";
648 $this->fatalError( $msg );
653 * Set triggers like when to try to run deferred updates
656 public function setAgentAndTriggers() {
657 if ( function_exists( 'posix_getpwuid' ) ) {
658 $agent = posix_getpwuid( posix_geteuid() )['name'];
662 $agent .= '@' . wfHostname();
664 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
665 // Add a comment for easy SHOW PROCESSLIST interpretation
666 $lbFactory->setAgentName(
667 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
669 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
673 * @param LBFactory $LBFactory
674 * @param Config $config
677 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
678 $services = MediaWikiServices
::getInstance();
679 $stats = $services->getStatsdDataFactory();
680 // Hook into period lag checks which often happen in long-running scripts
681 $lbFactory = $services->getDBLoadBalancerFactory();
682 $lbFactory->setWaitForReplicationListener(
684 function () use ( $stats, $config ) {
685 // Check config in case of JobRunner and unit tests
686 if ( $config->get( 'CommandLineMode' ) ) {
687 DeferredUpdates
::tryOpportunisticExecute( 'run' );
689 // Try to periodically flush buffered metrics to avoid OOMs
690 MediaWiki
::emitBufferedStatsdData( $stats, $config );
693 // Check for other windows to run them. A script may read or do a few writes
694 // to the master but mostly be writing to something else, like a file store.
695 $lbFactory->getMainLB()->setTransactionListener(
697 function ( $trigger ) use ( $stats, $config ) {
698 // Check config in case of JobRunner and unit tests
699 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
700 DeferredUpdates
::tryOpportunisticExecute( 'run' );
702 // Try to periodically flush buffered metrics to avoid OOMs
703 MediaWiki
::emitBufferedStatsdData( $stats, $config );
709 * Run a child maintenance script. Pass all of the current arguments
711 * @param string $maintClass A name of a child maintenance class
712 * @param string|null $classFile Full path of where the child is
713 * @return Maintenance
715 public function runChild( $maintClass, $classFile = null ) {
716 // Make sure the class is loaded first
717 if ( !class_exists( $maintClass ) ) {
719 require_once $classFile;
721 if ( !class_exists( $maintClass ) ) {
722 $this->error( "Cannot spawn child: $maintClass" );
727 * @var Maintenance $child
729 $child = new $maintClass();
730 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
731 if ( !is_null( $this->mDb
) ) {
732 $child->setDB( $this->mDb
);
739 * Do some sanity checking and basic setup
741 public function setup() {
742 global $IP, $wgCommandLineMode;
744 # Abort if called from a web server
745 # wfIsCLI() is not available yet
746 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
747 $this->fatalError( 'This script must be run from the command line' );
750 if ( $IP === null ) {
751 $this->fatalError( "\$IP not set, aborting!\n" .
752 '(Did you forget to call parent::__construct() in your maintenance script?)' );
755 # Make sure we can handle script parameters
756 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
757 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
760 // Send PHP warnings and errors to stderr instead of stdout.
761 // This aids in diagnosing problems, while keeping messages
762 // out of redirected output.
763 if ( ini_get( 'display_errors' ) ) {
764 ini_set( 'display_errors', 'stderr' );
767 $this->loadParamsAndArgs();
769 # Set the memory limit
770 # Note we need to set it again later in cache LocalSettings changed it
771 $this->adjustMemoryLimit();
773 # Set max execution time to 0 (no limit). PHP.net says that
774 # "When running PHP from the command line the default setting is 0."
775 # But sometimes this doesn't seem to be the case.
776 ini_set( 'max_execution_time', 0 );
778 # Define us as being in MediaWiki
779 define( 'MEDIAWIKI', true );
781 $wgCommandLineMode = true;
783 # Turn off output buffering if it's on
784 while ( ob_get_level() > 0 ) {
790 * Normally we disable the memory_limit when running admin scripts.
791 * Some scripts may wish to actually set a limit, however, to avoid
792 * blowing up unexpectedly. We also support a --memory-limit option,
793 * to allow sysadmins to explicitly set one if they'd prefer to override
794 * defaults (or for people using Suhosin which yells at you for trying
795 * to disable the limits)
798 public function memoryLimit() {
799 $limit = $this->getOption( 'memory-limit', 'max' );
800 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
805 * Adjusts PHP's memory limit to better suit our needs, if needed.
807 protected function adjustMemoryLimit() {
808 $limit = $this->memoryLimit();
809 if ( $limit == 'max' ) {
810 $limit = -1; // no memory limit
812 if ( $limit != 'default' ) {
813 ini_set( 'memory_limit', $limit );
818 * Activate the profiler (assuming $wgProfiler is set)
820 protected function activateProfiler() {
821 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
823 $output = $this->getOption( 'profiler' );
828 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
829 $class = $wgProfiler['class'];
830 /** @var Profiler $profiler */
831 $profiler = new $class(
832 [ 'sampling' => 1, 'output' => [ $output ] ]
834 +
[ 'threshold' => $wgProfileLimit ]
836 $profiler->setAllowOutput();
837 Profiler
::replaceStubInstance( $profiler );
840 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
841 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
842 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
846 * Clear all params and arguments.
848 public function clearParamsAndArgs() {
849 $this->mOptions
= [];
851 $this->mInputLoaded
= false;
855 * Load params and arguments from a given array
856 * of command-line arguments
861 public function loadWithArgv( $argv ) {
864 $this->orderedOptions
= [];
867 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
868 if ( $arg == '--' ) {
869 # End of options, remainder should be considered arguments
870 $arg = next( $argv );
871 while ( $arg !== false ) {
873 $arg = next( $argv );
876 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
878 $option = substr( $arg, 2 );
879 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
880 $param = next( $argv );
881 if ( $param === false ) {
882 $this->error( "\nERROR: $option parameter needs a value after it\n" );
883 $this->maybeHelp( true );
886 $this->setParam( $options, $option, $param );
888 $bits = explode( '=', $option, 2 );
889 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
891 } elseif ( $arg == '-' ) {
892 # Lonely "-", often used to indicate stdin or stdout.
894 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
896 $argLength = strlen( $arg );
897 for ( $p = 1; $p < $argLength; $p++
) {
899 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
900 $option = $this->mShortParamsMap
[$option];
903 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
904 $param = next( $argv );
905 if ( $param === false ) {
906 $this->error( "\nERROR: $option parameter needs a value after it\n" );
907 $this->maybeHelp( true );
909 $this->setParam( $options, $option, $param );
911 $this->setParam( $options, $option, 1 );
919 $this->mOptions
= $options;
920 $this->mArgs
= $args;
921 $this->loadSpecialVars();
922 $this->mInputLoaded
= true;
926 * Helper function used solely by loadParamsAndArgs
927 * to prevent code duplication
929 * This sets the param in the options array based on
930 * whether or not it can be specified multiple times.
933 * @param array $options
934 * @param string $option
935 * @param mixed $value
937 private function setParam( &$options, $option, $value ) {
938 $this->orderedOptions
[] = [ $option, $value ];
940 if ( isset( $this->mParams
[$option] ) ) {
941 $multi = $this->mParams
[$option]['multiOccurrence'];
945 $exists = array_key_exists( $option, $options );
946 if ( $multi && $exists ) {
947 $options[$option][] = $value;
948 } elseif ( $multi ) {
949 $options[$option] = [ $value ];
950 } elseif ( !$exists ) {
951 $options[$option] = $value;
953 $this->error( "\nERROR: $option parameter given twice\n" );
954 $this->maybeHelp( true );
959 * Process command line arguments
960 * $mOptions becomes an array with keys set to the option names
961 * $mArgs becomes a zero-based array containing the non-option arguments
963 * @param string|null $self The name of the script, if any
964 * @param array|null $opts An array of options, in form of key=>value
965 * @param array|null $args An array of command line arguments
967 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
968 # If we were given opts or args, set those and return early
970 $this->mSelf
= $self;
971 $this->mInputLoaded
= true;
974 $this->mOptions
= $opts;
975 $this->mInputLoaded
= true;
978 $this->mArgs
= $args;
979 $this->mInputLoaded
= true;
982 # If we've already loaded input (either by user values or from $argv)
983 # skip on loading it again. The array_shift() will corrupt values if
984 # it's run again and again
985 if ( $this->mInputLoaded
) {
986 $this->loadSpecialVars();
992 $this->mSelf
= $argv[0];
993 $this->loadWithArgv( array_slice( $argv, 1 ) );
997 * Run some validation checks on the params, etc
999 public function validateParamsAndArgs() {
1001 # Check to make sure we've got all the required options
1002 foreach ( $this->mParams
as $opt => $info ) {
1003 if ( $info['require'] && !$this->hasOption( $opt ) ) {
1004 $this->error( "Param $opt required!" );
1008 # Check arg list too
1009 foreach ( $this->mArgList
as $k => $info ) {
1010 if ( $info['require'] && !$this->hasArg( $k ) ) {
1011 $this->error( 'Argument <' . $info['name'] . '> required!' );
1015 if ( !$this->mAllowUnregisteredOptions
) {
1016 # Check for unexpected options
1017 foreach ( $this->mOptions
as $opt => $val ) {
1018 if ( !$this->supportsOption( $opt ) ) {
1019 $this->error( "Unexpected option $opt!" );
1025 $this->maybeHelp( $die );
1029 * Handle the special variables that are global to all scripts
1031 protected function loadSpecialVars() {
1032 if ( $this->hasOption( 'dbuser' ) ) {
1033 $this->mDbUser
= $this->getOption( 'dbuser' );
1035 if ( $this->hasOption( 'dbpass' ) ) {
1036 $this->mDbPass
= $this->getOption( 'dbpass' );
1038 if ( $this->hasOption( 'quiet' ) ) {
1039 $this->mQuiet
= true;
1041 if ( $this->hasOption( 'batch-size' ) ) {
1042 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1047 * Maybe show the help.
1048 * @param bool $force Whether to force the help to show, default false
1050 protected function maybeHelp( $force = false ) {
1051 if ( !$force && !$this->hasOption( 'help' ) ) {
1055 $screenWidth = 80; // TODO: Calculate this!
1057 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1059 ksort( $this->mParams
);
1060 $this->mQuiet
= false;
1063 if ( $this->mDescription
) {
1064 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1066 $output = "\nUsage: php " . basename( $this->mSelf
);
1068 // ... append parameters ...
1069 if ( $this->mParams
) {
1070 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1073 // ... and append arguments.
1074 if ( $this->mArgList
) {
1076 foreach ( $this->mArgList
as $k => $arg ) {
1077 if ( $arg['require'] ) {
1078 $output .= '<' . $arg['name'] . '>';
1080 $output .= '[' . $arg['name'] . ']';
1082 if ( $k < count( $this->mArgList
) - 1 ) {
1087 $this->output( "$output\n\n" );
1089 # TODO abstract some repetitive code below
1091 // Generic parameters
1092 $this->output( "Generic maintenance parameters:\n" );
1093 foreach ( $this->mGenericParameters
as $par => $info ) {
1094 if ( $info['shortName'] !== false ) {
1095 $par .= " (-{$info['shortName']})";
1098 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1099 "\n$tab$tab" ) . "\n"
1102 $this->output( "\n" );
1104 $scriptDependantParams = $this->mDependantParameters
;
1105 if ( count( $scriptDependantParams ) > 0 ) {
1106 $this->output( "Script dependant parameters:\n" );
1107 // Parameters description
1108 foreach ( $scriptDependantParams as $par => $info ) {
1109 if ( $info['shortName'] !== false ) {
1110 $par .= " (-{$info['shortName']})";
1113 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1114 "\n$tab$tab" ) . "\n"
1117 $this->output( "\n" );
1120 // Script specific parameters not defined on construction by
1121 // Maintenance::addDefaultParams()
1122 $scriptSpecificParams = array_diff_key(
1123 # all script parameters:
1125 # remove the Maintenance default parameters:
1126 $this->mGenericParameters
,
1127 $this->mDependantParameters
1129 if ( count( $scriptSpecificParams ) > 0 ) {
1130 $this->output( "Script specific parameters:\n" );
1131 // Parameters description
1132 foreach ( $scriptSpecificParams as $par => $info ) {
1133 if ( $info['shortName'] !== false ) {
1134 $par .= " (-{$info['shortName']})";
1137 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1138 "\n$tab$tab" ) . "\n"
1141 $this->output( "\n" );
1145 if ( count( $this->mArgList
) > 0 ) {
1146 $this->output( "Arguments:\n" );
1147 // Arguments description
1148 foreach ( $this->mArgList
as $info ) {
1149 $openChar = $info['require'] ?
'<' : '[';
1150 $closeChar = $info['require'] ?
'>' : ']';
1152 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1153 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1156 $this->output( "\n" );
1163 * Handle some last-minute setup here.
1165 public function finalSetup() {
1166 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1167 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1168 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1170 # Turn off output buffering again, it might have been turned on in the settings files
1171 if ( ob_get_level() ) {
1175 $wgCommandLineMode = true;
1177 # Override $wgServer
1178 if ( $this->hasOption( 'server' ) ) {
1179 $wgServer = $this->getOption( 'server', $wgServer );
1182 # If these were passed, use them
1183 if ( $this->mDbUser
) {
1184 $wgDBadminuser = $this->mDbUser
;
1186 if ( $this->mDbPass
) {
1187 $wgDBadminpassword = $this->mDbPass
;
1189 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1190 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1192 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1195 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1196 $wgDBuser = $wgDBadminuser;
1197 $wgDBpassword = $wgDBadminpassword;
1199 if ( $wgDBservers ) {
1201 * @var array $wgDBservers
1203 foreach ( $wgDBservers as $i => $server ) {
1204 $wgDBservers[$i]['user'] = $wgDBuser;
1205 $wgDBservers[$i]['password'] = $wgDBpassword;
1208 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1209 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1210 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1212 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1215 # Apply debug settings
1216 if ( $this->hasOption( 'mwdebug' ) ) {
1217 require __DIR__
. '/../includes/DevelopmentSettings.php';
1220 // Per-script profiling; useful for debugging
1221 $this->activateProfiler();
1223 $this->afterFinalSetup();
1225 $wgShowExceptionDetails = true;
1226 $wgShowHostnames = true;
1228 Wikimedia\
suppressWarnings();
1229 set_time_limit( 0 );
1230 Wikimedia\restoreWarnings
();
1232 $this->adjustMemoryLimit();
1236 * Execute a callback function at the end of initialisation
1238 protected function afterFinalSetup() {
1239 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1240 call_user_func( MW_CMDLINE_CALLBACK
);
1245 * Potentially debug globals. Originally a feature only
1248 public function globals() {
1249 if ( $this->hasOption( 'globals' ) ) {
1250 print_r( $GLOBALS );
1255 * Generic setup for most installs. Returns the location of LocalSettings
1258 public function loadSettings() {
1259 global $wgCommandLineMode, $IP;
1261 if ( isset( $this->mOptions
['conf'] ) ) {
1262 $settingsFile = $this->mOptions
['conf'];
1263 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1264 $settingsFile = MW_CONFIG_FILE
;
1266 $settingsFile = "$IP/LocalSettings.php";
1268 if ( isset( $this->mOptions
['wiki'] ) ) {
1269 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1270 define( 'MW_DB', $bits[0] );
1271 define( 'MW_PREFIX', $bits[1] ??
'' );
1272 } elseif ( isset( $this->mOptions
['server'] ) ) {
1273 // Provide the option for site admins to detect and configure
1274 // multiple wikis based on server names. This offers --server
1275 // as alternative to --wiki.
1276 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1277 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1280 if ( !is_readable( $settingsFile ) ) {
1281 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1282 "must exist and be readable in the source directory.\n" .
1283 "Use --conf to specify it." );
1285 $wgCommandLineMode = true;
1287 return $settingsFile;
1291 * Support function for cleaning up redundant text records
1292 * @param bool $delete Whether or not to actually delete the records
1293 * @author Rob Church <robchur@gmail.com>
1295 public function purgeRedundantText( $delete = true ) {
1296 global $wgMultiContentRevisionSchemaMigrationStage;
1298 # Data should come off the master, wrapped in a transaction
1299 $dbw = $this->getDB( DB_MASTER
);
1300 $this->beginTransaction( $dbw, __METHOD__
);
1302 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1303 # Get "active" text records from the revisions table
1305 $this->output( 'Searching for active text records in revisions table...' );
1306 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1307 foreach ( $res as $row ) {
1308 $cur[] = $row->rev_text_id
;
1310 $this->output( "done.\n" );
1312 # Get "active" text records from the archive table
1313 $this->output( 'Searching for active text records in archive table...' );
1314 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1315 foreach ( $res as $row ) {
1316 # old pre-MW 1.5 records can have null ar_text_id's.
1317 if ( $row->ar_text_id
!== null ) {
1318 $cur[] = $row->ar_text_id
;
1321 $this->output( "done.\n" );
1323 # Get "active" text records via the content table
1325 $this->output( 'Searching for active text records via contents table...' );
1326 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1327 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1328 foreach ( $res as $row ) {
1329 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1334 $this->output( "done.\n" );
1336 $this->output( "done.\n" );
1338 # Get the IDs of all text records not in these sets
1339 $this->output( 'Searching for inactive text records...' );
1340 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1341 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1343 foreach ( $res as $row ) {
1344 $old[] = $row->old_id
;
1346 $this->output( "done.\n" );
1348 # Inform the user of what we're going to do
1349 $count = count( $old );
1350 $this->output( "$count inactive items found.\n" );
1352 # Delete as appropriate
1353 if ( $delete && $count ) {
1354 $this->output( 'Deleting...' );
1355 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1356 $this->output( "done.\n" );
1359 $this->commitTransaction( $dbw, __METHOD__
);
1363 * Get the maintenance directory.
1366 protected function getDir() {
1371 * Returns a database to be used by current maintenance script.
1373 * This uses the main LBFactory instance by default unless overriden via setDB().
1375 * This function has the same parameters as LoadBalancer::getConnection().
1377 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1378 * @param string|string[] $groups default: empty array
1379 * @param string|bool $dbDomain default: current wiki
1380 * @return IMaintainableDatabase
1382 protected function getDB( $db, $groups = [], $dbDomain = false ) {
1383 if ( $this->mDb
=== null ) {
1384 return MediaWikiServices
::getInstance()
1385 ->getDBLoadBalancerFactory()
1386 ->getMainLB( $dbDomain )
1387 ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1394 * Sets database object to be returned by getDB().
1396 * @param IMaintainableDatabase $db
1398 public function setDB( IMaintainableDatabase
$db ) {
1403 * Begin a transcation on a DB
1405 * This method makes it clear that begin() is called from a maintenance script,
1406 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1408 * @param IDatabase $dbw
1409 * @param string $fname Caller name
1412 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1413 $dbw->begin( $fname );
1417 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1419 * This method makes it clear that commit() is called from a maintenance script,
1420 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1422 * @param IDatabase $dbw
1423 * @param string $fname Caller name
1424 * @return bool Whether the replica DB wait succeeded
1427 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1428 $dbw->commit( $fname );
1429 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1430 $waitSucceeded = $lbFactory->waitForReplication(
1431 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1433 $this->lastReplicationWait
= microtime( true );
1434 return $waitSucceeded;
1438 * Rollback the transcation on a DB handle
1440 * This method makes it clear that rollback() is called from a maintenance script,
1441 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1443 * @param IDatabase $dbw
1444 * @param string $fname Caller name
1447 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1448 $dbw->rollback( $fname );
1452 * Lock the search index
1453 * @param IMaintainableDatabase &$db
1455 private function lockSearchindex( $db ) {
1456 $write = [ 'searchindex' ];
1466 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1471 * @param IMaintainableDatabase &$db
1473 private function unlockSearchindex( $db ) {
1474 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1478 * Unlock and lock again
1479 * Since the lock is low-priority, queued reads will be able to complete
1480 * @param IMaintainableDatabase &$db
1482 private function relockSearchindex( $db ) {
1483 $this->unlockSearchindex( $db );
1484 $this->lockSearchindex( $db );
1488 * Perform a search index update with locking
1489 * @param int $maxLockTime The maximum time to keep the search index locked.
1490 * @param callable $callback The function that will update the function.
1491 * @param IMaintainableDatabase $dbw
1492 * @param array|IResultWrapper $results
1494 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1498 if ( $maxLockTime ) {
1499 $this->output( " --- Waiting for lock ---" );
1500 $this->lockSearchindex( $dbw );
1502 $this->output( "\n" );
1505 # Loop through the results and do a search update
1506 foreach ( $results as $row ) {
1507 # Allow reads to be processed
1508 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1509 $this->output( " --- Relocking ---" );
1510 $this->relockSearchindex( $dbw );
1512 $this->output( "\n" );
1514 call_user_func( $callback, $dbw, $row );
1517 # Unlock searchindex
1518 if ( $maxLockTime ) {
1519 $this->output( " --- Unlocking --" );
1520 $this->unlockSearchindex( $dbw );
1521 $this->output( "\n" );
1526 * Update the searchindex table for a given pageid
1527 * @param IDatabase $dbw A database write handle
1528 * @param int $pageId The page ID to update.
1529 * @return null|string
1531 public function updateSearchIndexForPage( $dbw, $pageId ) {
1532 // Get current revision
1533 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1536 $titleObj = $rev->getTitle();
1537 $title = $titleObj->getPrefixedDBkey();
1538 $this->output( "$title..." );
1539 # Update searchindex
1540 $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent() );
1542 $this->output( "\n" );
1549 * Count down from $seconds to zero on the terminal, with a one-second pause
1550 * between showing each number. If the maintenance script is in quiet mode,
1551 * this function does nothing.
1555 * @codeCoverageIgnore
1556 * @param int $seconds
1558 protected function countDown( $seconds ) {
1559 if ( $this->isQuiet() ) {
1562 for ( $i = $seconds; $i >= 0; $i-- ) {
1563 if ( $i != $seconds ) {
1564 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1566 $this->output( $i );
1571 $this->output( "\n" );
1575 * Wrapper for posix_isatty()
1576 * We default as considering stdin a tty (for nice readline methods)
1577 * but treating stout as not a tty to avoid color codes
1579 * @param mixed $fd File descriptor
1582 public static function posix_isatty( $fd ) {
1583 if ( !function_exists( 'posix_isatty' ) ) {
1586 return posix_isatty( $fd );
1591 * Prompt the console for input
1592 * @param string $prompt What to begin the line with, like '> '
1593 * @return string Response
1595 public static function readconsole( $prompt = '> ' ) {
1596 static $isatty = null;
1597 if ( is_null( $isatty ) ) {
1598 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1601 if ( $isatty && function_exists( 'readline' ) ) {
1602 return readline( $prompt );
1605 $st = self
::readlineEmulation( $prompt );
1607 if ( feof( STDIN
) ) {
1610 $st = fgets( STDIN
, 1024 );
1613 if ( $st === false ) {
1616 $resp = trim( $st );
1623 * Emulate readline()
1624 * @param string $prompt What to begin the line with, like '> '
1627 private static function readlineEmulation( $prompt ) {
1628 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1629 if ( !wfIsWindows() && $bash ) {
1631 $encPrompt = Shell
::escape( $prompt );
1632 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1633 $encCommand = Shell
::escape( $command );
1634 $line = Shell
::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1636 if ( $retval == 0 ) {
1638 } elseif ( $retval == 127 ) {
1639 // Couldn't execute bash even though we thought we saw it.
1640 // Shell probably spit out an error message, sorry :(
1641 // Fall through to fgets()...
1648 // Fallback... we'll have no editing controls, EWWW
1649 if ( feof( STDIN
) ) {
1654 return fgets( STDIN
, 1024 );
1658 * Get the terminal size as a two-element array where the first element
1659 * is the width (number of columns) and the second element is the height
1664 public static function getTermSize() {
1665 $default = [ 80, 50 ];
1666 if ( wfIsWindows() ) {
1669 if ( Shell
::isDisabled() ) {
1672 // It's possible to get the screen size with VT-100 terminal escapes,
1673 // but reading the responses is not possible without setting raw mode
1674 // (unless you want to require the user to press enter), and that
1675 // requires an ioctl(), which we can't do. So we have to shell out to
1676 // something that can do the relevant syscalls. There are a few
1677 // options. Linux and Mac OS X both have "stty size" which does the
1679 $result = Shell
::command( 'stty', 'size' )
1681 if ( $result->getExitCode() !== 0 ) {
1684 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1687 return [ intval( $m[2] ), intval( $m[1] ) ];
1691 * Call this to set up the autoloader to allow classes to be used from the
1694 public static function requireTestsAutoloader() {
1695 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1700 * Fake maintenance wrapper, mostly used for the web installer/updater
1702 class FakeMaintenance
extends Maintenance
{
1703 protected $mSelf = "FakeMaintenanceScript";
1705 public function execute() {
1710 * Class for scripts that perform database maintenance and want to log the
1711 * update in `updatelog` so we can later skip it
1713 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1714 public function __construct() {
1715 parent
::__construct();
1716 $this->addOption( 'force', 'Run the update even if it was completed already' );
1717 $this->setBatchSize( 200 );
1720 public function execute() {
1721 $db = $this->getDB( DB_MASTER
);
1722 $key = $this->getUpdateKey();
1724 if ( !$this->hasOption( 'force' )
1725 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1727 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1732 if ( !$this->doDBUpdates() ) {
1736 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, [ 'IGNORE' ] );
1742 * Message to show that the update was done already and was just skipped
1745 protected function updateSkippedMessage() {
1746 $key = $this->getUpdateKey();
1748 return "Update '{$key}' already logged as completed. Use --force to run it again.";
1752 * Do the actual work. All child classes will need to implement this.
1753 * Return true to log the update as done or false (usually on failure).
1756 abstract protected function doDBUpdates();
1759 * Get the update key name to go in the update log table
1762 abstract protected function getUpdateKey();