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 If > 0, go ahead and die out using this int as the code
403 protected function error( $err, $die = 0 ) {
404 $this->outputChanneled( false );
405 if ( PHP_SAPI
== 'cli' ) {
406 fwrite( STDERR
, $err . "\n" );
410 $die = intval( $die );
416 private $atLineStart = true;
417 private $lastChannel = null;
420 * Clean up channeled output. Output a newline if necessary.
422 public function cleanupChanneled() {
423 if ( !$this->atLineStart
) {
425 $this->atLineStart
= true;
430 * Message outputter with channeled message support. Messages on the
431 * same channel are concatenated, but any intervening messages in another
432 * channel start a new line.
433 * @param string $msg The message without trailing newline
434 * @param string $channel Channel identifier or null for no
435 * channel. Channel comparison uses ===.
437 public function outputChanneled( $msg, $channel = null ) {
438 if ( $msg === false ) {
439 $this->cleanupChanneled();
444 // End the current line if necessary
445 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
451 $this->atLineStart
= false;
452 if ( $channel === null ) {
453 // For unchanneled messages, output trailing newline immediately
455 $this->atLineStart
= true;
457 $this->lastChannel
= $channel;
461 * Does the script need different DB access? By default, we give Maintenance
462 * scripts normal rights to the DB. Sometimes, a script needs admin rights
463 * access for a reason and sometimes they want no access. Subclasses should
464 * override and return one of the following values, as needed:
465 * Maintenance::DB_NONE - For no DB access at all
466 * Maintenance::DB_STD - For normal DB access, default
467 * Maintenance::DB_ADMIN - For admin DB access
470 public function getDbType() {
475 * Add the default parameters to the scripts
477 protected function addDefaultParams() {
478 # Generic (non script dependant) options:
480 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
481 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
482 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
483 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
484 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
487 'Set a specific memory limit for the script, '
488 . '"max" for no limit or "default" to avoid changing it'
490 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
491 "http://en.wikipedia.org. This is sometimes necessary because " .
492 "server name detection may fail in command line scripts.", false, true );
493 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
495 # Save generic options to display them separately in help
496 $this->mGenericParameters
= $this->mParams
;
498 # Script dependant options:
500 // If we support a DB, show the options
501 if ( $this->getDbType() > 0 ) {
502 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
503 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
506 # Save additional script dependant options to display
507 # Â them separately in help
508 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
515 public function getConfig() {
516 if ( $this->config
=== null ) {
517 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
520 return $this->config
;
525 * @param Config $config
527 public function setConfig( Config
$config ) {
528 $this->config
= $config;
532 * Indicate that the specified extension must be
533 * loaded before the script can run.
535 * This *must* be called in the constructor.
538 * @param string $name
540 protected function requireExtension( $name ) {
541 $this->requiredExtensions
[] = $name;
545 * Verify that the required extensions are installed
549 public function checkRequiredExtensions() {
550 $registry = ExtensionRegistry
::getInstance();
552 foreach ( $this->requiredExtensions
as $name ) {
553 if ( !$registry->isLoaded( $name ) ) {
559 $joined = implode( ', ', $missing );
560 $msg = "The following extensions are required to be installed "
561 . "for this script to run: $joined. Please enable them and then try again.";
562 $this->error( $msg, 1 );
567 * Set triggers like when to try to run deferred updates
570 public function setAgentAndTriggers() {
571 if ( function_exists( 'posix_getpwuid' ) ) {
572 $agent = posix_getpwuid( posix_geteuid() )['name'];
576 $agent .= '@' . wfHostname();
578 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
579 // Add a comment for easy SHOW PROCESSLIST interpretation
580 $lbFactory->setAgentName(
581 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
583 self
::setLBFactoryTriggers( $lbFactory );
587 * @param LBFactory $LBFactory
590 public static function setLBFactoryTriggers( LBFactory
$LBFactory ) {
591 // Hook into period lag checks which often happen in long-running scripts
592 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
593 $lbFactory->setWaitForReplicationListener(
596 global $wgCommandLineMode;
597 // Check config in case of JobRunner and unit tests
598 if ( $wgCommandLineMode ) {
599 DeferredUpdates
::tryOpportunisticExecute( 'run' );
603 // Check for other windows to run them. A script may read or do a few writes
604 // to the master but mostly be writing to something else, like a file store.
605 $lbFactory->getMainLB()->setTransactionListener(
607 function ( $trigger ) {
608 global $wgCommandLineMode;
609 // Check config in case of JobRunner and unit tests
610 if ( $wgCommandLineMode && $trigger === IDatabase
::TRIGGER_COMMIT
) {
611 DeferredUpdates
::tryOpportunisticExecute( 'run' );
618 * Run a child maintenance script. Pass all of the current arguments
620 * @param string $maintClass A name of a child maintenance class
621 * @param string $classFile Full path of where the child is
622 * @return Maintenance
624 public function runChild( $maintClass, $classFile = null ) {
625 // Make sure the class is loaded first
626 if ( !class_exists( $maintClass ) ) {
628 require_once $classFile;
630 if ( !class_exists( $maintClass ) ) {
631 $this->error( "Cannot spawn child: $maintClass" );
636 * @var $child Maintenance
638 $child = new $maintClass();
639 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
640 if ( !is_null( $this->mDb
) ) {
641 $child->setDB( $this->mDb
);
648 * Do some sanity checking and basic setup
650 public function setup() {
651 global $IP, $wgCommandLineMode, $wgRequestTime;
653 # Abort if called from a web server
654 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
655 $this->error( 'This script must be run from the command line', true );
658 if ( $IP === null ) {
659 $this->error( "\$IP not set, aborting!\n" .
660 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
663 # Make sure we can handle script parameters
664 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
665 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
668 // Send PHP warnings and errors to stderr instead of stdout.
669 // This aids in diagnosing problems, while keeping messages
670 // out of redirected output.
671 if ( ini_get( 'display_errors' ) ) {
672 ini_set( 'display_errors', 'stderr' );
675 $this->loadParamsAndArgs();
678 # Set the memory limit
679 # Note we need to set it again later in cache LocalSettings changed it
680 $this->adjustMemoryLimit();
682 # Set max execution time to 0 (no limit). PHP.net says that
683 # "When running PHP from the command line the default setting is 0."
684 # But sometimes this doesn't seem to be the case.
685 ini_set( 'max_execution_time', 0 );
687 $wgRequestTime = microtime( true );
689 # Define us as being in MediaWiki
690 define( 'MEDIAWIKI', true );
692 $wgCommandLineMode = true;
694 # Turn off output buffering if it's on
695 while ( ob_get_level() > 0 ) {
699 $this->validateParamsAndArgs();
703 * Normally we disable the memory_limit when running admin scripts.
704 * Some scripts may wish to actually set a limit, however, to avoid
705 * blowing up unexpectedly. We also support a --memory-limit option,
706 * to allow sysadmins to explicitly set one if they'd prefer to override
707 * defaults (or for people using Suhosin which yells at you for trying
708 * to disable the limits)
711 public function memoryLimit() {
712 $limit = $this->getOption( 'memory-limit', 'max' );
713 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
718 * Adjusts PHP's memory limit to better suit our needs, if needed.
720 protected function adjustMemoryLimit() {
721 $limit = $this->memoryLimit();
722 if ( $limit == 'max' ) {
723 $limit = -1; // no memory limit
725 if ( $limit != 'default' ) {
726 ini_set( 'memory_limit', $limit );
731 * Activate the profiler (assuming $wgProfiler is set)
733 protected function activateProfiler() {
734 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
736 $output = $this->getOption( 'profiler' );
741 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
742 $class = $wgProfiler['class'];
743 /** @var Profiler $profiler */
744 $profiler = new $class(
745 [ 'sampling' => 1, 'output' => [ $output ] ]
747 +
[ 'threshold' => $wgProfileLimit ]
749 $profiler->setTemplated( true );
750 Profiler
::replaceStubInstance( $profiler );
753 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
754 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
755 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
759 * Clear all params and arguments.
761 public function clearParamsAndArgs() {
762 $this->mOptions
= [];
764 $this->mInputLoaded
= false;
768 * Load params and arguments from a given array
769 * of command-line arguments
774 public function loadWithArgv( $argv ) {
777 $this->orderedOptions
= [];
780 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
781 if ( $arg == '--' ) {
782 # End of options, remainder should be considered arguments
783 $arg = next( $argv );
784 while ( $arg !== false ) {
786 $arg = next( $argv );
789 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
791 $option = substr( $arg, 2 );
792 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
793 $param = next( $argv );
794 if ( $param === false ) {
795 $this->error( "\nERROR: $option parameter needs a value after it\n" );
796 $this->maybeHelp( true );
799 $this->setParam( $options, $option, $param );
801 $bits = explode( '=', $option, 2 );
802 if ( count( $bits ) > 1 ) {
809 $this->setParam( $options, $option, $param );
811 } elseif ( $arg == '-' ) {
812 # Lonely "-", often used to indicate stdin or stdout.
814 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
816 $argLength = strlen( $arg );
817 for ( $p = 1; $p < $argLength; $p++
) {
819 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
820 $option = $this->mShortParamsMap
[$option];
823 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
824 $param = next( $argv );
825 if ( $param === false ) {
826 $this->error( "\nERROR: $option parameter needs a value after it\n" );
827 $this->maybeHelp( true );
829 $this->setParam( $options, $option, $param );
831 $this->setParam( $options, $option, 1 );
839 $this->mOptions
= $options;
840 $this->mArgs
= $args;
841 $this->loadSpecialVars();
842 $this->mInputLoaded
= true;
846 * Helper function used solely by loadParamsAndArgs
847 * to prevent code duplication
849 * This sets the param in the options array based on
850 * whether or not it can be specified multiple times.
853 * @param array $options
854 * @param string $option
855 * @param mixed $value
857 private function setParam( &$options, $option, $value ) {
858 $this->orderedOptions
[] = [ $option, $value ];
860 if ( isset( $this->mParams
[$option] ) ) {
861 $multi = $this->mParams
[$option]['multiOccurrence'];
865 $exists = array_key_exists( $option, $options );
866 if ( $multi && $exists ) {
867 $options[$option][] = $value;
868 } elseif ( $multi ) {
869 $options[$option] = [ $value ];
870 } elseif ( !$exists ) {
871 $options[$option] = $value;
873 $this->error( "\nERROR: $option parameter given twice\n" );
874 $this->maybeHelp( true );
879 * Process command line arguments
880 * $mOptions becomes an array with keys set to the option names
881 * $mArgs becomes a zero-based array containing the non-option arguments
883 * @param string $self The name of the script, if any
884 * @param array $opts An array of options, in form of key=>value
885 * @param array $args An array of command line arguments
887 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
888 # If we were given opts or args, set those and return early
890 $this->mSelf
= $self;
891 $this->mInputLoaded
= true;
894 $this->mOptions
= $opts;
895 $this->mInputLoaded
= true;
898 $this->mArgs
= $args;
899 $this->mInputLoaded
= true;
902 # If we've already loaded input (either by user values or from $argv)
903 # skip on loading it again. The array_shift() will corrupt values if
904 # it's run again and again
905 if ( $this->mInputLoaded
) {
906 $this->loadSpecialVars();
912 $this->mSelf
= $argv[0];
913 $this->loadWithArgv( array_slice( $argv, 1 ) );
917 * Run some validation checks on the params, etc
919 protected function validateParamsAndArgs() {
921 # Check to make sure we've got all the required options
922 foreach ( $this->mParams
as $opt => $info ) {
923 if ( $info['require'] && !$this->hasOption( $opt ) ) {
924 $this->error( "Param $opt required!" );
929 foreach ( $this->mArgList
as $k => $info ) {
930 if ( $info['require'] && !$this->hasArg( $k ) ) {
931 $this->error( 'Argument <' . $info['name'] . '> required!' );
937 $this->maybeHelp( true );
942 * Handle the special variables that are global to all scripts
944 protected function loadSpecialVars() {
945 if ( $this->hasOption( 'dbuser' ) ) {
946 $this->mDbUser
= $this->getOption( 'dbuser' );
948 if ( $this->hasOption( 'dbpass' ) ) {
949 $this->mDbPass
= $this->getOption( 'dbpass' );
951 if ( $this->hasOption( 'quiet' ) ) {
952 $this->mQuiet
= true;
954 if ( $this->hasOption( 'batch-size' ) ) {
955 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
960 * Maybe show the help.
961 * @param bool $force Whether to force the help to show, default false
963 protected function maybeHelp( $force = false ) {
964 if ( !$force && !$this->hasOption( 'help' ) ) {
968 $screenWidth = 80; // TODO: Calculate this!
970 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
972 ksort( $this->mParams
);
973 $this->mQuiet
= false;
976 if ( $this->mDescription
) {
977 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
979 $output = "\nUsage: php " . basename( $this->mSelf
);
981 // ... append parameters ...
982 if ( $this->mParams
) {
983 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
986 // ... and append arguments.
987 if ( $this->mArgList
) {
989 foreach ( $this->mArgList
as $k => $arg ) {
990 if ( $arg['require'] ) {
991 $output .= '<' . $arg['name'] . '>';
993 $output .= '[' . $arg['name'] . ']';
995 if ( $k < count( $this->mArgList
) - 1 ) {
1000 $this->output( "$output\n\n" );
1002 # TODO abstract some repetitive code below
1004 // Generic parameters
1005 $this->output( "Generic maintenance parameters:\n" );
1006 foreach ( $this->mGenericParameters
as $par => $info ) {
1007 if ( $info['shortName'] !== false ) {
1008 $par .= " (-{$info['shortName']})";
1011 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1012 "\n$tab$tab" ) . "\n"
1015 $this->output( "\n" );
1017 $scriptDependantParams = $this->mDependantParameters
;
1018 if ( count( $scriptDependantParams ) > 0 ) {
1019 $this->output( "Script dependant parameters:\n" );
1020 // Parameters description
1021 foreach ( $scriptDependantParams as $par => $info ) {
1022 if ( $info['shortName'] !== false ) {
1023 $par .= " (-{$info['shortName']})";
1026 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1027 "\n$tab$tab" ) . "\n"
1030 $this->output( "\n" );
1033 // Script specific parameters not defined on construction by
1034 // Maintenance::addDefaultParams()
1035 $scriptSpecificParams = array_diff_key(
1036 # all script parameters:
1038 # remove the Maintenance default parameters:
1039 $this->mGenericParameters
,
1040 $this->mDependantParameters
1042 if ( count( $scriptSpecificParams ) > 0 ) {
1043 $this->output( "Script specific parameters:\n" );
1044 // Parameters description
1045 foreach ( $scriptSpecificParams as $par => $info ) {
1046 if ( $info['shortName'] !== false ) {
1047 $par .= " (-{$info['shortName']})";
1050 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1051 "\n$tab$tab" ) . "\n"
1054 $this->output( "\n" );
1058 if ( count( $this->mArgList
) > 0 ) {
1059 $this->output( "Arguments:\n" );
1060 // Arguments description
1061 foreach ( $this->mArgList
as $info ) {
1062 $openChar = $info['require'] ?
'<' : '[';
1063 $closeChar = $info['require'] ?
'>' : ']';
1065 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1066 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1069 $this->output( "\n" );
1076 * Handle some last-minute setup here.
1078 public function finalSetup() {
1079 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1080 global $wgDBadminuser, $wgDBadminpassword;
1081 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1083 # Turn off output buffering again, it might have been turned on in the settings files
1084 if ( ob_get_level() ) {
1088 $wgCommandLineMode = true;
1090 # Override $wgServer
1091 if ( $this->hasOption( 'server' ) ) {
1092 $wgServer = $this->getOption( 'server', $wgServer );
1095 # If these were passed, use them
1096 if ( $this->mDbUser
) {
1097 $wgDBadminuser = $this->mDbUser
;
1099 if ( $this->mDbPass
) {
1100 $wgDBadminpassword = $this->mDbPass
;
1103 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1104 $wgDBuser = $wgDBadminuser;
1105 $wgDBpassword = $wgDBadminpassword;
1107 if ( $wgDBservers ) {
1109 * @var $wgDBservers array
1111 foreach ( $wgDBservers as $i => $server ) {
1112 $wgDBservers[$i]['user'] = $wgDBuser;
1113 $wgDBservers[$i]['password'] = $wgDBpassword;
1116 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1117 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1118 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1120 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1123 // Per-script profiling; useful for debugging
1124 $this->activateProfiler();
1126 $this->afterFinalSetup();
1128 $wgShowSQLErrors = true;
1130 MediaWiki\
suppressWarnings();
1131 set_time_limit( 0 );
1132 MediaWiki\restoreWarnings
();
1134 $this->adjustMemoryLimit();
1138 * Execute a callback function at the end of initialisation
1140 protected function afterFinalSetup() {
1141 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1142 call_user_func( MW_CMDLINE_CALLBACK
);
1147 * Potentially debug globals. Originally a feature only
1150 public function globals() {
1151 if ( $this->hasOption( 'globals' ) ) {
1152 print_r( $GLOBALS );
1157 * Generic setup for most installs. Returns the location of LocalSettings
1160 public function loadSettings() {
1161 global $wgCommandLineMode, $IP;
1163 if ( isset( $this->mOptions
['conf'] ) ) {
1164 $settingsFile = $this->mOptions
['conf'];
1165 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1166 $settingsFile = MW_CONFIG_FILE
;
1168 $settingsFile = "$IP/LocalSettings.php";
1170 if ( isset( $this->mOptions
['wiki'] ) ) {
1171 $bits = explode( '-', $this->mOptions
['wiki'] );
1172 if ( count( $bits ) == 1 ) {
1175 define( 'MW_DB', $bits[0] );
1176 define( 'MW_PREFIX', $bits[1] );
1179 if ( !is_readable( $settingsFile ) ) {
1180 $this->error( "A copy of your installation's LocalSettings.php\n" .
1181 "must exist and be readable in the source directory.\n" .
1182 "Use --conf to specify it.", true );
1184 $wgCommandLineMode = true;
1186 return $settingsFile;
1190 * Support function for cleaning up redundant text records
1191 * @param bool $delete Whether or not to actually delete the records
1192 * @author Rob Church <robchur@gmail.com>
1194 public function purgeRedundantText( $delete = true ) {
1195 # Data should come off the master, wrapped in a transaction
1196 $dbw = $this->getDB( DB_MASTER
);
1197 $this->beginTransaction( $dbw, __METHOD__
);
1199 # Get "active" text records from the revisions table
1201 $this->output( 'Searching for active text records in revisions table...' );
1202 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1203 foreach ( $res as $row ) {
1204 $cur[] = $row->rev_text_id
;
1206 $this->output( "done.\n" );
1208 # Get "active" text records from the archive table
1209 $this->output( 'Searching for active text records in archive table...' );
1210 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1211 foreach ( $res as $row ) {
1212 # old pre-MW 1.5 records can have null ar_text_id's.
1213 if ( $row->ar_text_id
!== null ) {
1214 $cur[] = $row->ar_text_id
;
1217 $this->output( "done.\n" );
1219 # Get the IDs of all text records not in these sets
1220 $this->output( 'Searching for inactive text records...' );
1221 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1222 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1224 foreach ( $res as $row ) {
1225 $old[] = $row->old_id
;
1227 $this->output( "done.\n" );
1229 # Inform the user of what we're going to do
1230 $count = count( $old );
1231 $this->output( "$count inactive items found.\n" );
1233 # Delete as appropriate
1234 if ( $delete && $count ) {
1235 $this->output( 'Deleting...' );
1236 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1237 $this->output( "done.\n" );
1241 $this->commitTransaction( $dbw, __METHOD__
);
1245 * Get the maintenance directory.
1248 protected function getDir() {
1253 * Returns a database to be used by current maintenance script. It can be set by setDB().
1254 * If not set, wfGetDB() will be used.
1255 * This function has the same parameters as wfGetDB()
1257 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1258 * @param array $groups default: empty array
1259 * @param string|bool $wiki default: current wiki
1260 * @return IMaintainableDatabase
1262 protected function getDB( $db, $groups = [], $wiki = false ) {
1263 if ( is_null( $this->mDb
) ) {
1264 return wfGetDB( $db, $groups, $wiki );
1271 * Sets database object to be returned by getDB().
1273 * @param IDatabase $db
1275 public function setDB( IDatabase
$db ) {
1280 * Begin a transcation on a DB
1282 * This method makes it clear that begin() is called from a maintenance script,
1283 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1285 * @param IDatabase $dbw
1286 * @param string $fname Caller name
1289 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1290 $dbw->begin( $fname );
1294 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1296 * This method makes it clear that commit() is called from a maintenance script,
1297 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1299 * @param IDatabase $dbw
1300 * @param string $fname Caller name
1301 * @return bool Whether the replica DB wait succeeded
1304 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1305 $dbw->commit( $fname );
1307 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1308 $lbFactory->waitForReplication(
1309 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1311 $this->lastReplicationWait
= microtime( true );
1314 } catch ( DBReplicationWaitError
$e ) {
1320 * Rollback the transcation on a DB handle
1322 * This method makes it clear that rollback() is called from a maintenance script,
1323 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1325 * @param IDatabase $dbw
1326 * @param string $fname Caller name
1329 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1330 $dbw->rollback( $fname );
1334 * Lock the search index
1335 * @param IMaintainableDatabase &$db
1337 private function lockSearchindex( $db ) {
1338 $write = [ 'searchindex' ];
1348 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1353 * @param IMaintainableDatabase &$db
1355 private function unlockSearchindex( $db ) {
1356 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1360 * Unlock and lock again
1361 * Since the lock is low-priority, queued reads will be able to complete
1362 * @param IMaintainableDatabase &$db
1364 private function relockSearchindex( $db ) {
1365 $this->unlockSearchindex( $db );
1366 $this->lockSearchindex( $db );
1370 * Perform a search index update with locking
1371 * @param int $maxLockTime The maximum time to keep the search index locked.
1372 * @param string $callback The function that will update the function.
1373 * @param IMaintainableDatabase $dbw
1374 * @param array $results
1376 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1380 if ( $maxLockTime ) {
1381 $this->output( " --- Waiting for lock ---" );
1382 $this->lockSearchindex( $dbw );
1384 $this->output( "\n" );
1387 # Loop through the results and do a search update
1388 foreach ( $results as $row ) {
1389 # Allow reads to be processed
1390 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1391 $this->output( " --- Relocking ---" );
1392 $this->relockSearchindex( $dbw );
1394 $this->output( "\n" );
1396 call_user_func( $callback, $dbw, $row );
1399 # Unlock searchindex
1400 if ( $maxLockTime ) {
1401 $this->output( " --- Unlocking --" );
1402 $this->unlockSearchindex( $dbw );
1403 $this->output( "\n" );
1408 * Update the searchindex table for a given pageid
1409 * @param IDatabase $dbw A database write handle
1410 * @param int $pageId The page ID to update.
1411 * @return null|string
1413 public function updateSearchIndexForPage( $dbw, $pageId ) {
1414 // Get current revision
1415 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1418 $titleObj = $rev->getTitle();
1419 $title = $titleObj->getPrefixedDBkey();
1420 $this->output( "$title..." );
1421 # Update searchindex
1422 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1424 $this->output( "\n" );
1431 * Count down from $seconds to zero on the terminal, with a one-second pause
1432 * between showing each number. If the maintenance script is in quiet mode,
1433 * this function does nothing.
1437 * @codeCoverageIgnore
1438 * @param int $seconds
1440 protected function countDown( $seconds ) {
1441 if ( $this->isQuiet() ) {
1444 for ( $i = $seconds; $i >= 0; $i-- ) {
1445 if ( $i != $seconds ) {
1446 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1448 $this->output( $i );
1453 $this->output( "\n" );
1457 * Wrapper for posix_isatty()
1458 * We default as considering stdin a tty (for nice readline methods)
1459 * but treating stout as not a tty to avoid color codes
1461 * @param mixed $fd File descriptor
1464 public static function posix_isatty( $fd ) {
1465 if ( !function_exists( 'posix_isatty' ) ) {
1468 return posix_isatty( $fd );
1473 * Prompt the console for input
1474 * @param string $prompt What to begin the line with, like '> '
1475 * @return string Response
1477 public static function readconsole( $prompt = '> ' ) {
1478 static $isatty = null;
1479 if ( is_null( $isatty ) ) {
1480 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1483 if ( $isatty && function_exists( 'readline' ) ) {
1484 return readline( $prompt );
1487 $st = self
::readlineEmulation( $prompt );
1489 if ( feof( STDIN
) ) {
1492 $st = fgets( STDIN
, 1024 );
1495 if ( $st === false ) {
1498 $resp = trim( $st );
1505 * Emulate readline()
1506 * @param string $prompt What to begin the line with, like '> '
1509 private static function readlineEmulation( $prompt ) {
1510 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1511 if ( !wfIsWindows() && $bash ) {
1513 $encPrompt = wfEscapeShellArg( $prompt );
1514 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1515 $encCommand = wfEscapeShellArg( $command );
1516 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1518 if ( $retval == 0 ) {
1520 } elseif ( $retval == 127 ) {
1521 // Couldn't execute bash even though we thought we saw it.
1522 // Shell probably spit out an error message, sorry :(
1523 // Fall through to fgets()...
1530 // Fallback... we'll have no editing controls, EWWW
1531 if ( feof( STDIN
) ) {
1536 return fgets( STDIN
, 1024 );
1540 * Get the terminal size as a two-element array where the first element
1541 * is the width (number of columns) and the second element is the height
1546 public static function getTermSize() {
1547 $default = [ 80, 50 ];
1548 if ( wfIsWindows() ) {
1551 // It's possible to get the screen size with VT-100 terminal escapes,
1552 // but reading the responses is not possible without setting raw mode
1553 // (unless you want to require the user to press enter), and that
1554 // requires an ioctl(), which we can't do. So we have to shell out to
1555 // something that can do the relevant syscalls. There are a few
1556 // options. Linux and Mac OS X both have "stty size" which does the
1559 $size = wfShellExec( 'stty size', $retval );
1560 if ( $retval !== 0 ) {
1563 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1566 return [ intval( $m[2] ), intval( $m[1] ) ];
1570 * Call this to set up the autoloader to allow classes to be used from the
1573 public static function requireTestsAutoloader() {
1574 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1579 * Fake maintenance wrapper, mostly used for the web installer/updater
1581 class FakeMaintenance
extends Maintenance
{
1582 protected $mSelf = "FakeMaintenanceScript";
1584 public function execute() {
1590 * Class for scripts that perform database maintenance and want to log the
1591 * update in `updatelog` so we can later skip it
1593 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1594 public function __construct() {
1595 parent
::__construct();
1596 $this->addOption( 'force', 'Run the update even if it was completed already' );
1597 $this->setBatchSize( 200 );
1600 public function execute() {
1601 $db = $this->getDB( DB_MASTER
);
1602 $key = $this->getUpdateKey();
1604 if ( !$this->hasOption( 'force' )
1605 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1607 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1612 if ( !$this->doDBUpdates() ) {
1616 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1619 $this->output( $this->updatelogFailedMessage() . "\n" );
1626 * Message to show that the update was done already and was just skipped
1629 protected function updateSkippedMessage() {
1630 $key = $this->getUpdateKey();
1632 return "Update '{$key}' already logged as completed.";
1636 * Message to show that the update log was unable to log the completion of this update
1639 protected function updatelogFailedMessage() {
1640 $key = $this->getUpdateKey();
1642 return "Unable to log update '{$key}' as completed.";
1646 * Do the actual work. All child classes will need to implement this.
1647 * Return true to log the update as done or false (usually on failure).
1650 abstract protected function doDBUpdates();
1653 * Get the update key name to go in the update log table
1656 abstract protected function getUpdateKey();