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( 'text' );
28 use MediaWiki\Shell\Shell
;
29 use Wikimedia\Rdbms\IResultWrapper
;
32 * @defgroup MaintenanceArchive Maintenance archives
33 * @ingroup Maintenance
36 // Define this so scripts can easily find doMaintenance.php
37 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
40 * @deprecated since 1.31
42 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
46 // Some extensions rely on MW_INSTALL_PATH to find core files to include. Setting it here helps them
47 // if they're included by a core script (like DatabaseUpdater) after Maintenance.php has already
49 if ( strval( getenv( 'MW_INSTALL_PATH' ) ) === '' ) {
50 putenv( 'MW_INSTALL_PATH=' . realpath( __DIR__
. '/..' ) );
53 use Wikimedia\Rdbms\IDatabase
;
54 use MediaWiki\Logger\LoggerFactory
;
55 use MediaWiki\MediaWikiServices
;
56 use Wikimedia\Rdbms\LBFactory
;
57 use Wikimedia\Rdbms\IMaintainableDatabase
;
60 * Abstract maintenance class for quickly writing and churning out
61 * maintenance scripts with minimal effort. All that _must_ be defined
62 * is the execute() method. See docs/maintenance.txt for more info
63 * and a quick demo of how to use it.
66 * params: registry of named values that may be passed to the script
67 * arg list: registry of positional values that may be passed to the script
68 * options: passed param values
69 * args: passed positional values
72 * mwscript somescript.php --foo=bar baz
74 * bar is the option value of the option for param foo
75 * baz is the arg value at index 0 in the arg list
78 * @ingroup Maintenance
80 abstract class Maintenance
{
82 * Constants for DB access type
83 * @see Maintenance::getDbType()
89 // Const for getStdin()
90 const STDIN_ALL
= 'all';
93 * Array of desired/allowed params
95 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string,multiOccurrence:bool}>
97 protected $mParams = [];
99 // Array of mapping short parameters to long ones
100 protected $mShortParamsMap = [];
102 // Array of desired/allowed args
103 protected $mArgList = [];
105 // This is the list of options that were actually passed
106 protected $mOptions = [];
108 // This is the list of arguments that were actually passed
109 protected $mArgs = [];
111 // Allow arbitrary options to be passed, or only specified ones?
112 protected $mAllowUnregisteredOptions = false;
114 // Name of the script currently running
117 // Special vars for params that are always used
118 protected $mQuiet = false;
119 protected $mDbUser, $mDbPass;
121 // A description of the script, children should change this via addDescription()
122 protected $mDescription = '';
124 // Have we already loaded our user input?
125 protected $mInputLoaded = false;
128 * Batch size. If a script supports this, they should set
129 * a default with setBatchSize()
133 protected $mBatchSize = null;
136 * Generic options added by addDefaultParams()
138 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string,multiOccurrence:bool}>
140 private $mGenericParameters = [];
142 * Generic options which might or not be supported by the script
144 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string,multiOccurrence:bool}>
146 private $mDependantParameters = [];
149 * Used by getDB() / setDB()
150 * @var IMaintainableDatabase
154 /** @var float UNIX timestamp */
155 private $lastReplicationWait = 0.0;
158 * Used when creating separate schema files.
164 * Accessible via getConfig()
171 * @see Maintenance::requireExtension
174 private $requiredExtensions = [];
177 * Used to read the options in the order they were passed.
178 * Useful for option chaining (Ex. dumpBackup.php). It will
179 * be an empty array if the options are passed in through
180 * loadParamsAndArgs( $self, $opts, $args ).
182 * This is an array of arrays where
183 * 0 => the option and 1 => parameter value.
187 public $orderedOptions = [];
190 * Default constructor. Children should call this *first* if implementing
191 * their own constructors
193 public function __construct() {
195 $IP = getenv( 'MW_INSTALL_PATH' );
197 $this->addDefaultParams();
198 register_shutdown_function( [ $this, 'outputChanneled' ], false );
202 * Should we execute the maintenance script, or just allow it to be included
203 * as a standalone class? It checks that the call stack only includes this
204 * function and "requires" (meaning was called from the file scope)
208 public static function shouldExecute() {
209 global $wgCommandLineMode;
211 if ( !function_exists( 'debug_backtrace' ) ) {
212 // If someone has a better idea...
213 return $wgCommandLineMode;
216 $bt = debug_backtrace();
217 $count = count( $bt );
219 return false; // sanity
221 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
222 return false; // last call should be to this function
224 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
225 for ( $i = 1; $i < $count; $i++
) {
226 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
227 return false; // previous calls should all be "requires"
235 * Do the actual work. All child classes will need to implement this
237 * @return bool|null|void True for success, false for failure. Not returning
238 * a value, or returning null, is also interpreted as success. Returning
239 * false for failure will cause doMaintenance.php to exit the process
240 * with a non-zero exit status.
242 abstract public function execute();
245 * Checks to see if a particular option in supported. Normally this means it
246 * has been registered by the script via addOption.
247 * @param string $name The name of the option
248 * @return bool true if the option exists, false otherwise
250 protected function supportsOption( $name ) {
251 return isset( $this->mParams
[$name] );
255 * Add a parameter to the script. Will be displayed on --help
256 * with the associated description
258 * @param string $name The name of the param (help, version, etc)
259 * @param string $description The description of the param to show on --help
260 * @param bool $required Is the param required?
261 * @param bool $withArg Is an argument required with this option?
262 * @param string|bool $shortName Character to use as short name
263 * @param bool $multiOccurrence Can this option be passed multiple times?
265 protected function addOption( $name, $description, $required = false,
266 $withArg = false, $shortName = false, $multiOccurrence = false
268 $this->mParams
[$name] = [
269 'desc' => $description,
270 'require' => $required,
271 'withArg' => $withArg,
272 'shortName' => $shortName,
273 'multiOccurrence' => $multiOccurrence
276 if ( $shortName !== false ) {
277 $this->mShortParamsMap
[$shortName] = $name;
282 * Checks to see if a particular option exists.
283 * @param string $name The name of the option
286 protected function hasOption( $name ) {
287 return isset( $this->mOptions
[$name] );
291 * Get an option, or return the default.
293 * If the option was added to support multiple occurrences,
294 * this will return an array.
296 * @param string $name The name of the param
297 * @param mixed|null $default Anything you want, default null
300 protected function getOption( $name, $default = null ) {
301 if ( $this->hasOption( $name ) ) {
302 return $this->mOptions
[$name];
304 // Set it so we don't have to provide the default again
305 $this->mOptions
[$name] = $default;
307 return $this->mOptions
[$name];
312 * Add some args that are needed
313 * @param string $arg Name of the arg, like 'start'
314 * @param string $description Short description of the arg
315 * @param bool $required Is this required?
317 protected function addArg( $arg, $description, $required = true ) {
318 $this->mArgList
[] = [
320 'desc' => $description,
321 'require' => $required
326 * Remove an option. Useful for removing options that won't be used in your script.
327 * @param string $name The option to remove.
329 protected function deleteOption( $name ) {
330 unset( $this->mParams
[$name] );
334 * Sets whether to allow unregistered options, which are options passed to
335 * a script that do not match an expected parameter.
336 * @param bool $allow Should we allow?
338 protected function setAllowUnregisteredOptions( $allow ) {
339 $this->mAllowUnregisteredOptions
= $allow;
343 * Set the description text.
344 * @param string $text The text of the description
346 protected function addDescription( $text ) {
347 $this->mDescription
= $text;
351 * Does a given argument exist?
352 * @param int $argId The integer value (from zero) for the arg
355 protected function hasArg( $argId = 0 ) {
356 if ( func_num_args() === 0 ) {
357 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
360 return isset( $this->mArgs
[$argId] );
365 * @param int $argId The integer value (from zero) for the arg
366 * @param mixed|null $default The default if it doesn't exist
369 protected function getArg( $argId = 0, $default = null ) {
370 if ( func_num_args() === 0 ) {
371 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
374 return $this->mArgs
[$argId] ??
$default;
384 protected function getBatchSize() {
385 return $this->mBatchSize
;
389 * Set the batch size.
390 * @param int $s The number of operations to do in a batch
392 protected function setBatchSize( $s = 0 ) {
393 $this->mBatchSize
= $s;
395 // If we support $mBatchSize, show the option.
396 // Used to be in addDefaultParams, but in order for that to
397 // work, subclasses would have to call this function in the constructor
398 // before they called parent::__construct which is just weird
399 // (and really wasn't done).
400 if ( $this->mBatchSize
) {
401 $this->addOption( 'batch-size', 'Run this many operations ' .
402 'per batch, default: ' . $this->mBatchSize
, false, true );
403 if ( isset( $this->mParams
['batch-size'] ) ) {
404 // This seems a little ugly...
405 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
411 * Get the script's name
414 public function getName() {
419 * Return input from stdin.
420 * @param int|null $len The number of bytes to read. If null, just return the handle.
421 * Maintenance::STDIN_ALL returns the full length
424 protected function getStdin( $len = null ) {
425 if ( $len == self
::STDIN_ALL
) {
426 return file_get_contents( 'php://stdin' );
428 $f = fopen( 'php://stdin', 'rt' );
432 $input = fgets( $f, $len );
435 return rtrim( $input );
441 public function isQuiet() {
442 return $this->mQuiet
;
446 * Throw some output to the user. Scripts can call this with no fears,
447 * as we handle all --quiet stuff here
448 * @param string $out The text to show to the user
449 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
451 protected function output( $out, $channel = null ) {
452 // This is sometimes called very early, before Setup.php is included.
453 if ( class_exists( MediaWikiServices
::class ) ) {
454 // Try to periodically flush buffered metrics to avoid OOMs
455 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
456 if ( $stats->getDataCount() > 1000 ) {
457 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
461 if ( $this->mQuiet
) {
464 if ( $channel === null ) {
465 $this->cleanupChanneled();
468 $out = preg_replace( '/\n\z/', '', $out );
469 $this->outputChanneled( $out, $channel );
474 * Throw an error to the user. Doesn't respect --quiet, so don't use
475 * this for non-error output
476 * @param string $err The error to display
477 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
479 protected function error( $err, $die = 0 ) {
480 if ( intval( $die ) !== 0 ) {
481 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
482 $this->fatalError( $err, intval( $die ) );
484 $this->outputChanneled( false );
486 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
487 !defined( 'MW_PHPUNIT_TEST' )
489 fwrite( STDERR
, $err . "\n" );
496 * Output a message and terminate the current script.
498 * @param string $msg Error message
499 * @param int $exitCode PHP exit status. Should be in range 1-254.
502 protected function fatalError( $msg, $exitCode = 1 ) {
503 $this->error( $msg );
507 private $atLineStart = true;
508 private $lastChannel = null;
511 * Clean up channeled output. Output a newline if necessary.
513 public function cleanupChanneled() {
514 if ( !$this->atLineStart
) {
516 $this->atLineStart
= true;
521 * Message outputter with channeled message support. Messages on the
522 * same channel are concatenated, but any intervening messages in another
523 * channel start a new line.
524 * @param string $msg The message without trailing newline
525 * @param string|null $channel Channel identifier or null for no
526 * channel. Channel comparison uses ===.
528 public function outputChanneled( $msg, $channel = null ) {
529 if ( $msg === false ) {
530 $this->cleanupChanneled();
535 // End the current line if necessary
536 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
542 $this->atLineStart
= false;
543 if ( $channel === null ) {
544 // For unchanneled messages, output trailing newline immediately
546 $this->atLineStart
= true;
548 $this->lastChannel
= $channel;
552 * Does the script need different DB access? By default, we give Maintenance
553 * scripts normal rights to the DB. Sometimes, a script needs admin rights
554 * access for a reason and sometimes they want no access. Subclasses should
555 * override and return one of the following values, as needed:
556 * Maintenance::DB_NONE - For no DB access at all
557 * Maintenance::DB_STD - For normal DB access, default
558 * Maintenance::DB_ADMIN - For admin DB access
561 public function getDbType() {
566 * Add the default parameters to the scripts
568 protected function addDefaultParams() {
569 # Generic (non script dependant) options:
571 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
572 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
573 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
574 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
575 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
578 'Set a specific memory limit for the script, '
579 . '"max" for no limit or "default" to avoid changing it',
583 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
584 "http://en.wikipedia.org. This is sometimes necessary because " .
585 "server name detection may fail in command line scripts.", false, true );
586 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
587 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
588 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
590 # Save generic options to display them separately in help
591 $this->mGenericParameters
= $this->mParams
;
593 # Script dependant options:
595 // If we support a DB, show the options
596 if ( $this->getDbType() > 0 ) {
597 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
598 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
599 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
602 # Save additional script dependant options to display
603 # Â them separately in help
604 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
611 public function getConfig() {
612 if ( $this->config
=== null ) {
613 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
616 return $this->config
;
621 * @param Config $config
623 public function setConfig( Config
$config ) {
624 $this->config
= $config;
628 * Indicate that the specified extension must be
629 * loaded before the script can run.
631 * This *must* be called in the constructor.
634 * @param string $name
636 protected function requireExtension( $name ) {
637 $this->requiredExtensions
[] = $name;
641 * Verify that the required extensions are installed
645 public function checkRequiredExtensions() {
646 $registry = ExtensionRegistry
::getInstance();
648 foreach ( $this->requiredExtensions
as $name ) {
649 if ( !$registry->isLoaded( $name ) ) {
655 $joined = implode( ', ', $missing );
656 $msg = "The following extensions are required to be installed "
657 . "for this script to run: $joined. Please enable them and then try again.";
658 $this->fatalError( $msg );
663 * Set triggers like when to try to run deferred updates
666 public function setAgentAndTriggers() {
667 if ( function_exists( 'posix_getpwuid' ) ) {
668 $agent = posix_getpwuid( posix_geteuid() )['name'];
672 $agent .= '@' . wfHostname();
674 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
675 // Add a comment for easy SHOW PROCESSLIST interpretation
676 $lbFactory->setAgentName(
677 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
679 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
683 * @param LBFactory $LBFactory
684 * @param Config $config
687 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
688 $services = MediaWikiServices
::getInstance();
689 $stats = $services->getStatsdDataFactory();
690 // Hook into period lag checks which often happen in long-running scripts
691 $lbFactory = $services->getDBLoadBalancerFactory();
692 $lbFactory->setWaitForReplicationListener(
694 function () use ( $stats, $config ) {
695 // Check config in case of JobRunner and unit tests
696 if ( $config->get( 'CommandLineMode' ) ) {
697 DeferredUpdates
::tryOpportunisticExecute( 'run' );
699 // Try to periodically flush buffered metrics to avoid OOMs
700 MediaWiki
::emitBufferedStatsdData( $stats, $config );
703 // Check for other windows to run them. A script may read or do a few writes
704 // to the master but mostly be writing to something else, like a file store.
705 $lbFactory->getMainLB()->setTransactionListener(
707 function ( $trigger ) use ( $stats, $config ) {
708 // Check config in case of JobRunner and unit tests
709 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
710 DeferredUpdates
::tryOpportunisticExecute( 'run' );
712 // Try to periodically flush buffered metrics to avoid OOMs
713 MediaWiki
::emitBufferedStatsdData( $stats, $config );
719 * Run a child maintenance script. Pass all of the current arguments
721 * @param string $maintClass A name of a child maintenance class
722 * @param string|null $classFile Full path of where the child is
723 * @return Maintenance
725 public function runChild( $maintClass, $classFile = null ) {
726 // Make sure the class is loaded first
727 if ( !class_exists( $maintClass ) ) {
729 require_once $classFile;
731 if ( !class_exists( $maintClass ) ) {
732 $this->error( "Cannot spawn child: $maintClass" );
737 * @var Maintenance $child
739 $child = new $maintClass();
740 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
741 if ( !is_null( $this->mDb
) ) {
742 $child->setDB( $this->mDb
);
749 * Do some sanity checking and basic setup
751 public function setup() {
752 global $IP, $wgCommandLineMode;
754 # Abort if called from a web server
755 # wfIsCLI() is not available yet
756 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
757 $this->fatalError( 'This script must be run from the command line' );
760 if ( $IP === null ) {
761 $this->fatalError( "\$IP not set, aborting!\n" .
762 '(Did you forget to call parent::__construct() in your maintenance script?)' );
765 # Make sure we can handle script parameters
766 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
767 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
770 // Send PHP warnings and errors to stderr instead of stdout.
771 // This aids in diagnosing problems, while keeping messages
772 // out of redirected output.
773 if ( ini_get( 'display_errors' ) ) {
774 ini_set( 'display_errors', 'stderr' );
777 $this->loadParamsAndArgs();
779 # Set the memory limit
780 # Note we need to set it again later in cache LocalSettings changed it
781 $this->adjustMemoryLimit();
783 # Set max execution time to 0 (no limit). PHP.net says that
784 # "When running PHP from the command line the default setting is 0."
785 # But sometimes this doesn't seem to be the case.
786 ini_set( 'max_execution_time', 0 );
788 # Define us as being in MediaWiki
789 define( 'MEDIAWIKI', true );
791 $wgCommandLineMode = true;
793 # Turn off output buffering if it's on
794 while ( ob_get_level() > 0 ) {
800 * Normally we disable the memory_limit when running admin scripts.
801 * Some scripts may wish to actually set a limit, however, to avoid
802 * blowing up unexpectedly. We also support a --memory-limit option,
803 * to allow sysadmins to explicitly set one if they'd prefer to override
804 * defaults (or for people using Suhosin which yells at you for trying
805 * to disable the limits)
808 public function memoryLimit() {
809 $limit = $this->getOption( 'memory-limit', 'max' );
810 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
815 * Adjusts PHP's memory limit to better suit our needs, if needed.
817 protected function adjustMemoryLimit() {
818 $limit = $this->memoryLimit();
819 if ( $limit == 'max' ) {
820 $limit = -1; // no memory limit
822 if ( $limit != 'default' ) {
823 ini_set( 'memory_limit', $limit );
828 * Activate the profiler (assuming $wgProfiler is set)
830 protected function activateProfiler() {
831 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
833 $output = $this->getOption( 'profiler' );
838 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
839 $class = $wgProfiler['class'];
840 /** @var Profiler $profiler */
841 $profiler = new $class(
842 [ 'sampling' => 1, 'output' => [ $output ] ]
844 +
[ 'threshold' => $wgProfileLimit ]
846 $profiler->setAllowOutput();
847 Profiler
::replaceStubInstance( $profiler );
850 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
851 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
852 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
856 * Clear all params and arguments.
858 public function clearParamsAndArgs() {
859 $this->mOptions
= [];
861 $this->mInputLoaded
= false;
865 * Load params and arguments from a given array
866 * of command-line arguments
871 public function loadWithArgv( $argv ) {
874 $this->orderedOptions
= [];
877 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
878 if ( $arg == '--' ) {
879 # End of options, remainder should be considered arguments
880 $arg = next( $argv );
881 while ( $arg !== false ) {
883 $arg = next( $argv );
886 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
888 $option = substr( $arg, 2 );
889 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
890 $param = next( $argv );
891 if ( $param === false ) {
892 $this->error( "\nERROR: $option parameter needs a value after it\n" );
893 $this->maybeHelp( true );
896 $this->setParam( $options, $option, $param );
898 $bits = explode( '=', $option, 2 );
899 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
901 } elseif ( $arg == '-' ) {
902 # Lonely "-", often used to indicate stdin or stdout.
904 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
906 $argLength = strlen( $arg );
907 for ( $p = 1; $p < $argLength; $p++
) {
909 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
910 $option = $this->mShortParamsMap
[$option];
913 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
914 $param = next( $argv );
915 if ( $param === false ) {
916 $this->error( "\nERROR: $option parameter needs a value after it\n" );
917 $this->maybeHelp( true );
919 $this->setParam( $options, $option, $param );
921 $this->setParam( $options, $option, 1 );
929 $this->mOptions
= $options;
930 $this->mArgs
= $args;
931 $this->loadSpecialVars();
932 $this->mInputLoaded
= true;
936 * Helper function used solely by loadParamsAndArgs
937 * to prevent code duplication
939 * This sets the param in the options array based on
940 * whether or not it can be specified multiple times.
943 * @param array $options
944 * @param string $option
945 * @param mixed $value
947 private function setParam( &$options, $option, $value ) {
948 $this->orderedOptions
[] = [ $option, $value ];
950 if ( isset( $this->mParams
[$option] ) ) {
951 $multi = $this->mParams
[$option]['multiOccurrence'];
955 $exists = array_key_exists( $option, $options );
956 if ( $multi && $exists ) {
957 $options[$option][] = $value;
958 } elseif ( $multi ) {
959 $options[$option] = [ $value ];
960 } elseif ( !$exists ) {
961 $options[$option] = $value;
963 $this->error( "\nERROR: $option parameter given twice\n" );
964 $this->maybeHelp( true );
969 * Process command line arguments
970 * $mOptions becomes an array with keys set to the option names
971 * $mArgs becomes a zero-based array containing the non-option arguments
973 * @param string|null $self The name of the script, if any
974 * @param array|null $opts An array of options, in form of key=>value
975 * @param array|null $args An array of command line arguments
977 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
978 # If we were given opts or args, set those and return early
980 $this->mSelf
= $self;
981 $this->mInputLoaded
= true;
984 $this->mOptions
= $opts;
985 $this->mInputLoaded
= true;
988 $this->mArgs
= $args;
989 $this->mInputLoaded
= true;
992 # If we've already loaded input (either by user values or from $argv)
993 # skip on loading it again. The array_shift() will corrupt values if
994 # it's run again and again
995 if ( $this->mInputLoaded
) {
996 $this->loadSpecialVars();
1002 $this->mSelf
= $argv[0];
1003 $this->loadWithArgv( array_slice( $argv, 1 ) );
1007 * Run some validation checks on the params, etc
1009 public function validateParamsAndArgs() {
1011 # Check to make sure we've got all the required options
1012 foreach ( $this->mParams
as $opt => $info ) {
1013 if ( $info['require'] && !$this->hasOption( $opt ) ) {
1014 $this->error( "Param $opt required!" );
1018 # Check arg list too
1019 foreach ( $this->mArgList
as $k => $info ) {
1020 if ( $info['require'] && !$this->hasArg( $k ) ) {
1021 $this->error( 'Argument <' . $info['name'] . '> required!' );
1025 if ( !$this->mAllowUnregisteredOptions
) {
1026 # Check for unexpected options
1027 foreach ( $this->mOptions
as $opt => $val ) {
1028 if ( !$this->supportsOption( $opt ) ) {
1029 $this->error( "Unexpected option $opt!" );
1035 $this->maybeHelp( $die );
1039 * Handle the special variables that are global to all scripts
1041 protected function loadSpecialVars() {
1042 if ( $this->hasOption( 'dbuser' ) ) {
1043 $this->mDbUser
= $this->getOption( 'dbuser' );
1045 if ( $this->hasOption( 'dbpass' ) ) {
1046 $this->mDbPass
= $this->getOption( 'dbpass' );
1048 if ( $this->hasOption( 'quiet' ) ) {
1049 $this->mQuiet
= true;
1051 if ( $this->hasOption( 'batch-size' ) ) {
1052 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1057 * Maybe show the help.
1058 * @param bool $force Whether to force the help to show, default false
1060 protected function maybeHelp( $force = false ) {
1061 if ( !$force && !$this->hasOption( 'help' ) ) {
1065 $screenWidth = 80; // TODO: Calculate this!
1067 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1069 ksort( $this->mParams
);
1070 $this->mQuiet
= false;
1073 if ( $this->mDescription
) {
1074 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1076 $output = "\nUsage: php " . basename( $this->mSelf
);
1078 // ... append parameters ...
1079 if ( $this->mParams
) {
1080 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1083 // ... and append arguments.
1084 if ( $this->mArgList
) {
1086 foreach ( $this->mArgList
as $k => $arg ) {
1087 if ( $arg['require'] ) {
1088 $output .= '<' . $arg['name'] . '>';
1090 $output .= '[' . $arg['name'] . ']';
1092 if ( $k < count( $this->mArgList
) - 1 ) {
1097 $this->output( "$output\n\n" );
1099 # TODO abstract some repetitive code below
1101 // Generic parameters
1102 $this->output( "Generic maintenance parameters:\n" );
1103 foreach ( $this->mGenericParameters
as $par => $info ) {
1104 if ( $info['shortName'] !== false ) {
1105 $par .= " (-{$info['shortName']})";
1108 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1109 "\n$tab$tab" ) . "\n"
1112 $this->output( "\n" );
1114 $scriptDependantParams = $this->mDependantParameters
;
1115 if ( count( $scriptDependantParams ) > 0 ) {
1116 $this->output( "Script dependant parameters:\n" );
1117 // Parameters description
1118 foreach ( $scriptDependantParams as $par => $info ) {
1119 if ( $info['shortName'] !== false ) {
1120 $par .= " (-{$info['shortName']})";
1123 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1124 "\n$tab$tab" ) . "\n"
1127 $this->output( "\n" );
1130 // Script specific parameters not defined on construction by
1131 // Maintenance::addDefaultParams()
1132 $scriptSpecificParams = array_diff_key(
1133 # all script parameters:
1135 # remove the Maintenance default parameters:
1136 $this->mGenericParameters
,
1137 $this->mDependantParameters
1139 if ( count( $scriptSpecificParams ) > 0 ) {
1140 $this->output( "Script specific parameters:\n" );
1141 // Parameters description
1142 foreach ( $scriptSpecificParams as $par => $info ) {
1143 if ( $info['shortName'] !== false ) {
1144 $par .= " (-{$info['shortName']})";
1147 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1148 "\n$tab$tab" ) . "\n"
1151 $this->output( "\n" );
1155 if ( count( $this->mArgList
) > 0 ) {
1156 $this->output( "Arguments:\n" );
1157 // Arguments description
1158 foreach ( $this->mArgList
as $info ) {
1159 $openChar = $info['require'] ?
'<' : '[';
1160 $closeChar = $info['require'] ?
'>' : ']';
1162 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1163 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1166 $this->output( "\n" );
1173 * Handle some last-minute setup here.
1175 public function finalSetup() {
1176 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1177 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1178 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1180 # Turn off output buffering again, it might have been turned on in the settings files
1181 if ( ob_get_level() ) {
1185 $wgCommandLineMode = true;
1187 # Override $wgServer
1188 if ( $this->hasOption( 'server' ) ) {
1189 $wgServer = $this->getOption( 'server', $wgServer );
1192 # If these were passed, use them
1193 if ( $this->mDbUser
) {
1194 $wgDBadminuser = $this->mDbUser
;
1196 if ( $this->mDbPass
) {
1197 $wgDBadminpassword = $this->mDbPass
;
1199 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1200 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1202 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1205 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1206 $wgDBuser = $wgDBadminuser;
1207 $wgDBpassword = $wgDBadminpassword;
1209 if ( $wgDBservers ) {
1211 * @var array $wgDBservers
1213 foreach ( $wgDBservers as $i => $server ) {
1214 $wgDBservers[$i]['user'] = $wgDBuser;
1215 $wgDBservers[$i]['password'] = $wgDBpassword;
1218 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1219 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1220 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1222 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1225 # Apply debug settings
1226 if ( $this->hasOption( 'mwdebug' ) ) {
1227 require __DIR__
. '/../includes/DevelopmentSettings.php';
1230 // Per-script profiling; useful for debugging
1231 $this->activateProfiler();
1233 $this->afterFinalSetup();
1235 $wgShowExceptionDetails = true;
1236 $wgShowHostnames = true;
1238 Wikimedia\
suppressWarnings();
1239 set_time_limit( 0 );
1240 Wikimedia\restoreWarnings
();
1242 $this->adjustMemoryLimit();
1246 * Execute a callback function at the end of initialisation
1248 protected function afterFinalSetup() {
1249 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1250 // @phan-suppress-next-line PhanUndeclaredConstant
1251 call_user_func( MW_CMDLINE_CALLBACK
);
1256 * Potentially debug globals. Originally a feature only
1259 public function globals() {
1260 if ( $this->hasOption( 'globals' ) ) {
1261 print_r( $GLOBALS );
1266 * Generic setup for most installs. Returns the location of LocalSettings
1269 public function loadSettings() {
1270 global $wgCommandLineMode, $IP;
1272 if ( isset( $this->mOptions
['conf'] ) ) {
1273 $settingsFile = $this->mOptions
['conf'];
1274 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1275 $settingsFile = MW_CONFIG_FILE
;
1277 $settingsFile = "$IP/LocalSettings.php";
1279 if ( isset( $this->mOptions
['wiki'] ) ) {
1280 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1281 define( 'MW_DB', $bits[0] );
1282 define( 'MW_PREFIX', $bits[1] ??
'' );
1283 } elseif ( isset( $this->mOptions
['server'] ) ) {
1284 // Provide the option for site admins to detect and configure
1285 // multiple wikis based on server names. This offers --server
1286 // as alternative to --wiki.
1287 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1288 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1291 if ( !is_readable( $settingsFile ) ) {
1292 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1293 "must exist and be readable in the source directory.\n" .
1294 "Use --conf to specify it." );
1296 $wgCommandLineMode = true;
1298 return $settingsFile;
1302 * Support function for cleaning up redundant text records
1303 * @param bool $delete Whether or not to actually delete the records
1304 * @author Rob Church <robchur@gmail.com>
1306 public function purgeRedundantText( $delete = true ) {
1307 global $wgMultiContentRevisionSchemaMigrationStage;
1309 # Data should come off the master, wrapped in a transaction
1310 $dbw = $this->getDB( DB_MASTER
);
1311 $this->beginTransaction( $dbw, __METHOD__
);
1313 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1314 # Get "active" text records from the revisions table
1316 $this->output( 'Searching for active text records in revisions table...' );
1317 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1318 foreach ( $res as $row ) {
1319 $cur[] = $row->rev_text_id
;
1321 $this->output( "done.\n" );
1323 # Get "active" text records from the archive table
1324 $this->output( 'Searching for active text records in archive table...' );
1325 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1326 foreach ( $res as $row ) {
1327 # old pre-MW 1.5 records can have null ar_text_id's.
1328 if ( $row->ar_text_id
!== null ) {
1329 $cur[] = $row->ar_text_id
;
1332 $this->output( "done.\n" );
1334 # Get "active" text records via the content table
1336 $this->output( 'Searching for active text records via contents table...' );
1337 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1338 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1339 foreach ( $res as $row ) {
1340 // @phan-suppress-next-line PhanUndeclaredMethod
1341 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1346 $this->output( "done.\n" );
1348 $this->output( "done.\n" );
1350 # Get the IDs of all text records not in these sets
1351 $this->output( 'Searching for inactive text records...' );
1352 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1353 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1355 foreach ( $res as $row ) {
1356 $old[] = $row->old_id
;
1358 $this->output( "done.\n" );
1360 # Inform the user of what we're going to do
1361 $count = count( $old );
1362 $this->output( "$count inactive items found.\n" );
1364 # Delete as appropriate
1365 if ( $delete && $count ) {
1366 $this->output( 'Deleting...' );
1367 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1368 $this->output( "done.\n" );
1371 $this->commitTransaction( $dbw, __METHOD__
);
1375 * Get the maintenance directory.
1378 protected function getDir() {
1383 * Returns a database to be used by current maintenance script.
1385 * This uses the main LBFactory instance by default unless overriden via setDB().
1387 * This function has the same parameters as LoadBalancer::getConnection().
1389 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1390 * @param string|string[] $groups default: empty array
1391 * @param string|bool $dbDomain default: current wiki
1392 * @return IMaintainableDatabase
1394 protected function getDB( $db, $groups = [], $dbDomain = false ) {
1395 if ( $this->mDb
=== null ) {
1396 return MediaWikiServices
::getInstance()
1397 ->getDBLoadBalancerFactory()
1398 ->getMainLB( $dbDomain )
1399 ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1406 * Sets database object to be returned by getDB().
1408 * @param IMaintainableDatabase $db
1410 public function setDB( IMaintainableDatabase
$db ) {
1415 * Begin a transcation on a DB
1417 * This method makes it clear that begin() is called from a maintenance script,
1418 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1420 * @param IDatabase $dbw
1421 * @param string $fname Caller name
1424 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1425 $dbw->begin( $fname );
1429 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1431 * This method makes it clear that commit() is called from a maintenance script,
1432 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1434 * @param IDatabase $dbw
1435 * @param string $fname Caller name
1436 * @return bool Whether the replica DB wait succeeded
1439 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1440 $dbw->commit( $fname );
1441 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1442 $waitSucceeded = $lbFactory->waitForReplication(
1443 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1445 $this->lastReplicationWait
= microtime( true );
1446 return $waitSucceeded;
1450 * Rollback the transcation on a DB handle
1452 * This method makes it clear that rollback() is called from a maintenance script,
1453 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1455 * @param IDatabase $dbw
1456 * @param string $fname Caller name
1459 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1460 $dbw->rollback( $fname );
1464 * Lock the search index
1465 * @param IMaintainableDatabase &$db
1467 private function lockSearchindex( $db ) {
1468 $write = [ 'searchindex' ];
1478 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1483 * @param IMaintainableDatabase &$db
1485 private function unlockSearchindex( $db ) {
1486 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1490 * Unlock and lock again
1491 * Since the lock is low-priority, queued reads will be able to complete
1492 * @param IMaintainableDatabase &$db
1494 private function relockSearchindex( $db ) {
1495 $this->unlockSearchindex( $db );
1496 $this->lockSearchindex( $db );
1500 * Perform a search index update with locking
1501 * @param int $maxLockTime The maximum time to keep the search index locked.
1502 * @param callable $callback The function that will update the function.
1503 * @param IMaintainableDatabase $dbw
1504 * @param array|IResultWrapper $results
1506 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1510 if ( $maxLockTime ) {
1511 $this->output( " --- Waiting for lock ---" );
1512 $this->lockSearchindex( $dbw );
1514 $this->output( "\n" );
1517 # Loop through the results and do a search update
1518 foreach ( $results as $row ) {
1519 # Allow reads to be processed
1520 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1521 $this->output( " --- Relocking ---" );
1522 $this->relockSearchindex( $dbw );
1524 $this->output( "\n" );
1526 call_user_func( $callback, $dbw, $row );
1529 # Unlock searchindex
1530 if ( $maxLockTime ) {
1531 $this->output( " --- Unlocking --" );
1532 $this->unlockSearchindex( $dbw );
1533 $this->output( "\n" );
1538 * Update the searchindex table for a given pageid
1539 * @param IDatabase $dbw A database write handle
1540 * @param int $pageId The page ID to update.
1541 * @return null|string
1543 public function updateSearchIndexForPage( $dbw, $pageId ) {
1544 // Get current revision
1545 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1548 $titleObj = $rev->getTitle();
1549 $title = $titleObj->getPrefixedDBkey();
1550 $this->output( "$title..." );
1551 # Update searchindex
1552 $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent() );
1554 $this->output( "\n" );
1561 * Count down from $seconds to zero on the terminal, with a one-second pause
1562 * between showing each number. If the maintenance script is in quiet mode,
1563 * this function does nothing.
1567 * @codeCoverageIgnore
1568 * @param int $seconds
1570 protected function countDown( $seconds ) {
1571 if ( $this->isQuiet() ) {
1574 for ( $i = $seconds; $i >= 0; $i-- ) {
1575 if ( $i != $seconds ) {
1576 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1578 $this->output( $i );
1583 $this->output( "\n" );
1587 * Wrapper for posix_isatty()
1588 * We default as considering stdin a tty (for nice readline methods)
1589 * but treating stout as not a tty to avoid color codes
1591 * @param mixed $fd File descriptor
1594 public static function posix_isatty( $fd ) {
1595 if ( !function_exists( 'posix_isatty' ) ) {
1598 return posix_isatty( $fd );
1603 * Prompt the console for input
1604 * @param string $prompt What to begin the line with, like '> '
1605 * @return string Response
1607 public static function readconsole( $prompt = '> ' ) {
1608 static $isatty = null;
1609 if ( is_null( $isatty ) ) {
1610 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1613 if ( $isatty && function_exists( 'readline' ) ) {
1614 return readline( $prompt );
1617 $st = self
::readlineEmulation( $prompt );
1619 if ( feof( STDIN
) ) {
1622 $st = fgets( STDIN
, 1024 );
1625 if ( $st === false ) {
1628 $resp = trim( $st );
1635 * Emulate readline()
1636 * @param string $prompt What to begin the line with, like '> '
1639 private static function readlineEmulation( $prompt ) {
1640 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1641 if ( !wfIsWindows() && $bash ) {
1643 $encPrompt = Shell
::escape( $prompt );
1644 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1645 $encCommand = Shell
::escape( $command );
1646 $line = Shell
::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1648 if ( $retval == 0 ) {
1650 } elseif ( $retval == 127 ) {
1651 // Couldn't execute bash even though we thought we saw it.
1652 // Shell probably spit out an error message, sorry :(
1653 // Fall through to fgets()...
1660 // Fallback... we'll have no editing controls, EWWW
1661 if ( feof( STDIN
) ) {
1666 return fgets( STDIN
, 1024 );
1670 * Get the terminal size as a two-element array where the first element
1671 * is the width (number of columns) and the second element is the height
1676 public static function getTermSize() {
1677 $default = [ 80, 50 ];
1678 if ( wfIsWindows() ) {
1681 if ( Shell
::isDisabled() ) {
1684 // It's possible to get the screen size with VT-100 terminal escapes,
1685 // but reading the responses is not possible without setting raw mode
1686 // (unless you want to require the user to press enter), and that
1687 // requires an ioctl(), which we can't do. So we have to shell out to
1688 // something that can do the relevant syscalls. There are a few
1689 // options. Linux and Mac OS X both have "stty size" which does the
1691 $result = Shell
::command( 'stty', 'size' )
1693 if ( $result->getExitCode() !== 0 ) {
1696 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1699 return [ intval( $m[2] ), intval( $m[1] ) ];
1703 * Call this to set up the autoloader to allow classes to be used from the
1706 public static function requireTestsAutoloader() {
1707 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1712 * Fake maintenance wrapper, mostly used for the web installer/updater
1714 class FakeMaintenance
extends Maintenance
{
1715 protected $mSelf = "FakeMaintenanceScript";
1717 public function execute() {
1722 * Class for scripts that perform database maintenance and want to log the
1723 * update in `updatelog` so we can later skip it
1725 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1726 public function __construct() {
1727 parent
::__construct();
1728 $this->addOption( 'force', 'Run the update even if it was completed already' );
1729 $this->setBatchSize( 200 );
1732 public function execute() {
1733 $db = $this->getDB( DB_MASTER
);
1734 $key = $this->getUpdateKey();
1736 if ( !$this->hasOption( 'force' )
1737 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1739 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1744 if ( !$this->doDBUpdates() ) {
1748 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, [ 'IGNORE' ] );
1754 * Message to show that the update was done already and was just skipped
1757 protected function updateSkippedMessage() {
1758 $key = $this->getUpdateKey();
1760 return "Update '{$key}' already logged as completed. Use --force to run it again.";
1764 * Do the actual work. All child classes will need to implement this.
1765 * Return true to log the update as done or false (usually on failure).
1768 abstract protected function doDBUpdates();
1771 * Get the update key name to go in the update log table
1774 abstract protected function getUpdateKey();