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';
95 * Array of desired/allowed params
97 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string,multiOccurrence:bool}>
99 protected $mParams = [];
101 // Array of mapping short parameters to long ones
102 protected $mShortParamsMap = [];
104 // Array of desired/allowed args
105 protected $mArgList = [];
107 // This is the list of options that were actually passed
108 protected $mOptions = [];
110 // This is the list of arguments that were actually passed
111 protected $mArgs = [];
113 // Allow arbitrary options to be passed, or only specified ones?
114 protected $mAllowUnregisteredOptions = false;
116 // Name of the script currently running
119 // Special vars for params that are always used
120 protected $mQuiet = false;
121 protected $mDbUser, $mDbPass;
123 // A description of the script, children should change this via addDescription()
124 protected $mDescription = '';
126 // Have we already loaded our user input?
127 protected $mInputLoaded = false;
130 * Batch size. If a script supports this, they should set
131 * a default with setBatchSize()
135 protected $mBatchSize = null;
138 * Generic options added by addDefaultParams()
140 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string,multiOccurrence:bool}>
142 private $mGenericParameters = [];
144 * Generic options which might or not be supported by the script
146 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string,multiOccurrence:bool}>
148 private $mDependantParameters = [];
151 * Used by getDB() / setDB()
152 * @var IMaintainableDatabase
156 /** @var float UNIX timestamp */
157 private $lastReplicationWait = 0.0;
160 * Used when creating separate schema files.
166 * Accessible via getConfig()
173 * @see Maintenance::requireExtension
176 private $requiredExtensions = [];
179 * Used to read the options in the order they were passed.
180 * Useful for option chaining (Ex. dumpBackup.php). It will
181 * be an empty array if the options are passed in through
182 * loadParamsAndArgs( $self, $opts, $args ).
184 * This is an array of arrays where
185 * 0 => the option and 1 => parameter value.
189 public $orderedOptions = [];
192 * Default constructor. Children should call this *first* if implementing
193 * their own constructors
195 public function __construct() {
197 $IP = getenv( 'MW_INSTALL_PATH' );
199 $this->addDefaultParams();
200 register_shutdown_function( [ $this, 'outputChanneled' ], false );
204 * Should we execute the maintenance script, or just allow it to be included
205 * as a standalone class? It checks that the call stack only includes this
206 * function and "requires" (meaning was called from the file scope)
210 public static function shouldExecute() {
211 global $wgCommandLineMode;
213 if ( !function_exists( 'debug_backtrace' ) ) {
214 // If someone has a better idea...
215 return $wgCommandLineMode;
218 $bt = debug_backtrace();
219 $count = count( $bt );
221 return false; // sanity
223 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
224 return false; // last call should be to this function
226 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
227 for ( $i = 1; $i < $count; $i++
) {
228 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
229 return false; // previous calls should all be "requires"
237 * Do the actual work. All child classes will need to implement this
239 * @return bool|null|void True for success, false for failure. Not returning
240 * a value, or returning null, is also interpreted as success. Returning
241 * false for failure will cause doMaintenance.php to exit the process
242 * with a non-zero exit status.
244 abstract public function execute();
247 * Checks to see if a particular option in supported. Normally this means it
248 * has been registered by the script via addOption.
249 * @param string $name The name of the option
250 * @return bool true if the option exists, false otherwise
252 protected function supportsOption( $name ) {
253 return isset( $this->mParams
[$name] );
257 * Add a parameter to the script. Will be displayed on --help
258 * with the associated description
260 * @param string $name The name of the param (help, version, etc)
261 * @param string $description The description of the param to show on --help
262 * @param bool $required Is the param required?
263 * @param bool $withArg Is an argument required with this option?
264 * @param string|bool $shortName Character to use as short name
265 * @param bool $multiOccurrence Can this option be passed multiple times?
267 protected function addOption( $name, $description, $required = false,
268 $withArg = false, $shortName = false, $multiOccurrence = false
270 $this->mParams
[$name] = [
271 'desc' => $description,
272 'require' => $required,
273 'withArg' => $withArg,
274 'shortName' => $shortName,
275 'multiOccurrence' => $multiOccurrence
278 if ( $shortName !== false ) {
279 $this->mShortParamsMap
[$shortName] = $name;
284 * Checks to see if a particular option exists.
285 * @param string $name The name of the option
288 protected function hasOption( $name ) {
289 return isset( $this->mOptions
[$name] );
293 * Get an option, or return the default.
295 * If the option was added to support multiple occurrences,
296 * this will return an array.
298 * @param string $name The name of the param
299 * @param mixed|null $default Anything you want, default null
302 protected function getOption( $name, $default = null ) {
303 if ( $this->hasOption( $name ) ) {
304 return $this->mOptions
[$name];
306 // Set it so we don't have to provide the default again
307 $this->mOptions
[$name] = $default;
309 return $this->mOptions
[$name];
314 * Add some args that are needed
315 * @param string $arg Name of the arg, like 'start'
316 * @param string $description Short description of the arg
317 * @param bool $required Is this required?
319 protected function addArg( $arg, $description, $required = true ) {
320 $this->mArgList
[] = [
322 'desc' => $description,
323 'require' => $required
328 * Remove an option. Useful for removing options that won't be used in your script.
329 * @param string $name The option to remove.
331 protected function deleteOption( $name ) {
332 unset( $this->mParams
[$name] );
336 * Sets whether to allow unregistered options, which are options passed to
337 * a script that do not match an expected parameter.
338 * @param bool $allow Should we allow?
340 protected function setAllowUnregisteredOptions( $allow ) {
341 $this->mAllowUnregisteredOptions
= $allow;
345 * Set the description text.
346 * @param string $text The text of the description
348 protected function addDescription( $text ) {
349 $this->mDescription
= $text;
353 * Does a given argument exist?
354 * @param int $argId The integer value (from zero) for the arg
357 protected function hasArg( $argId = 0 ) {
358 if ( func_num_args() === 0 ) {
359 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
362 return isset( $this->mArgs
[$argId] );
367 * @param int $argId The integer value (from zero) for the arg
368 * @param mixed|null $default The default if it doesn't exist
371 protected function getArg( $argId = 0, $default = null ) {
372 if ( func_num_args() === 0 ) {
373 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
376 return $this->mArgs
[$argId] ??
$default;
386 protected function getBatchSize() {
387 return $this->mBatchSize
;
391 * Set the batch size.
392 * @param int $s The number of operations to do in a batch
394 protected function setBatchSize( $s = 0 ) {
395 $this->mBatchSize
= $s;
397 // If we support $mBatchSize, show the option.
398 // Used to be in addDefaultParams, but in order for that to
399 // work, subclasses would have to call this function in the constructor
400 // before they called parent::__construct which is just weird
401 // (and really wasn't done).
402 if ( $this->mBatchSize
) {
403 $this->addOption( 'batch-size', 'Run this many operations ' .
404 'per batch, default: ' . $this->mBatchSize
, false, true );
405 if ( isset( $this->mParams
['batch-size'] ) ) {
406 // This seems a little ugly...
407 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
413 * Get the script's name
416 public function getName() {
421 * Return input from stdin.
422 * @param int|null $len The number of bytes to read. If null, just return the handle.
423 * Maintenance::STDIN_ALL returns the full length
426 protected function getStdin( $len = null ) {
427 if ( $len == self
::STDIN_ALL
) {
428 return file_get_contents( 'php://stdin' );
430 $f = fopen( 'php://stdin', 'rt' );
434 $input = fgets( $f, $len );
437 return rtrim( $input );
443 public function isQuiet() {
444 return $this->mQuiet
;
448 * Throw some output to the user. Scripts can call this with no fears,
449 * as we handle all --quiet stuff here
450 * @param string $out The text to show to the user
451 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
453 protected function output( $out, $channel = null ) {
454 // This is sometimes called very early, before Setup.php is included.
455 if ( class_exists( MediaWikiServices
::class ) ) {
456 // Try to periodically flush buffered metrics to avoid OOMs
457 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
458 if ( $stats->getDataCount() > 1000 ) {
459 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
463 if ( $this->mQuiet
) {
466 if ( $channel === null ) {
467 $this->cleanupChanneled();
470 $out = preg_replace( '/\n\z/', '', $out );
471 $this->outputChanneled( $out, $channel );
476 * Throw an error to the user. Doesn't respect --quiet, so don't use
477 * this for non-error output
478 * @param string $err The error to display
479 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
481 protected function error( $err, $die = 0 ) {
482 if ( intval( $die ) !== 0 ) {
483 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
484 $this->fatalError( $err, intval( $die ) );
486 $this->outputChanneled( false );
488 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
489 !defined( 'MW_PHPUNIT_TEST' )
491 fwrite( STDERR
, $err . "\n" );
498 * Output a message and terminate the current script.
500 * @param string $msg Error message
501 * @param int $exitCode PHP exit status. Should be in range 1-254.
504 protected function fatalError( $msg, $exitCode = 1 ) {
505 $this->error( $msg );
509 private $atLineStart = true;
510 private $lastChannel = null;
513 * Clean up channeled output. Output a newline if necessary.
515 public function cleanupChanneled() {
516 if ( !$this->atLineStart
) {
518 $this->atLineStart
= true;
523 * Message outputter with channeled message support. Messages on the
524 * same channel are concatenated, but any intervening messages in another
525 * channel start a new line.
526 * @param string $msg The message without trailing newline
527 * @param string|null $channel Channel identifier or null for no
528 * channel. Channel comparison uses ===.
530 public function outputChanneled( $msg, $channel = null ) {
531 if ( $msg === false ) {
532 $this->cleanupChanneled();
537 // End the current line if necessary
538 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
544 $this->atLineStart
= false;
545 if ( $channel === null ) {
546 // For unchanneled messages, output trailing newline immediately
548 $this->atLineStart
= true;
550 $this->lastChannel
= $channel;
554 * Does the script need different DB access? By default, we give Maintenance
555 * scripts normal rights to the DB. Sometimes, a script needs admin rights
556 * access for a reason and sometimes they want no access. Subclasses should
557 * override and return one of the following values, as needed:
558 * Maintenance::DB_NONE - For no DB access at all
559 * Maintenance::DB_STD - For normal DB access, default
560 * Maintenance::DB_ADMIN - For admin DB access
563 public function getDbType() {
568 * Add the default parameters to the scripts
570 protected function addDefaultParams() {
571 # Generic (non script dependant) options:
573 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
574 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
575 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
576 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
577 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
580 'Set a specific memory limit for the script, '
581 . '"max" for no limit or "default" to avoid changing it',
585 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
586 "http://en.wikipedia.org. This is sometimes necessary because " .
587 "server name detection may fail in command line scripts.", false, true );
588 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
589 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
590 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
592 # Save generic options to display them separately in help
593 $this->mGenericParameters
= $this->mParams
;
595 # Script dependant options:
597 // If we support a DB, show the options
598 if ( $this->getDbType() > 0 ) {
599 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
600 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
601 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
604 # Save additional script dependant options to display
605 # Â them separately in help
606 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
613 public function getConfig() {
614 if ( $this->config
=== null ) {
615 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
618 return $this->config
;
623 * @param Config $config
625 public function setConfig( Config
$config ) {
626 $this->config
= $config;
630 * Indicate that the specified extension must be
631 * loaded before the script can run.
633 * This *must* be called in the constructor.
636 * @param string $name
638 protected function requireExtension( $name ) {
639 $this->requiredExtensions
[] = $name;
643 * Verify that the required extensions are installed
647 public function checkRequiredExtensions() {
648 $registry = ExtensionRegistry
::getInstance();
650 foreach ( $this->requiredExtensions
as $name ) {
651 if ( !$registry->isLoaded( $name ) ) {
657 $joined = implode( ', ', $missing );
658 $msg = "The following extensions are required to be installed "
659 . "for this script to run: $joined. Please enable them and then try again.";
660 $this->fatalError( $msg );
665 * Set triggers like when to try to run deferred updates
668 public function setAgentAndTriggers() {
669 if ( function_exists( 'posix_getpwuid' ) ) {
670 $agent = posix_getpwuid( posix_geteuid() )['name'];
674 $agent .= '@' . wfHostname();
676 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
677 // Add a comment for easy SHOW PROCESSLIST interpretation
678 $lbFactory->setAgentName(
679 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
681 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
685 * @param LBFactory $LBFactory
686 * @param Config $config
689 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
690 $services = MediaWikiServices
::getInstance();
691 $stats = $services->getStatsdDataFactory();
692 // Hook into period lag checks which often happen in long-running scripts
693 $lbFactory = $services->getDBLoadBalancerFactory();
694 $lbFactory->setWaitForReplicationListener(
696 function () use ( $stats, $config ) {
697 // Check config in case of JobRunner and unit tests
698 if ( $config->get( 'CommandLineMode' ) ) {
699 DeferredUpdates
::tryOpportunisticExecute( 'run' );
701 // Try to periodically flush buffered metrics to avoid OOMs
702 MediaWiki
::emitBufferedStatsdData( $stats, $config );
705 // Check for other windows to run them. A script may read or do a few writes
706 // to the master but mostly be writing to something else, like a file store.
707 $lbFactory->getMainLB()->setTransactionListener(
709 function ( $trigger ) use ( $stats, $config ) {
710 // Check config in case of JobRunner and unit tests
711 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
712 DeferredUpdates
::tryOpportunisticExecute( 'run' );
714 // Try to periodically flush buffered metrics to avoid OOMs
715 MediaWiki
::emitBufferedStatsdData( $stats, $config );
721 * Run a child maintenance script. Pass all of the current arguments
723 * @param string $maintClass A name of a child maintenance class
724 * @param string|null $classFile Full path of where the child is
725 * @return Maintenance
727 public function runChild( $maintClass, $classFile = null ) {
728 // Make sure the class is loaded first
729 if ( !class_exists( $maintClass ) ) {
731 require_once $classFile;
733 if ( !class_exists( $maintClass ) ) {
734 $this->error( "Cannot spawn child: $maintClass" );
739 * @var Maintenance $child
741 $child = new $maintClass();
742 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
743 if ( !is_null( $this->mDb
) ) {
744 $child->setDB( $this->mDb
);
751 * Do some sanity checking and basic setup
753 public function setup() {
754 global $IP, $wgCommandLineMode;
756 # Abort if called from a web server
757 # wfIsCLI() is not available yet
758 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
759 $this->fatalError( 'This script must be run from the command line' );
762 if ( $IP === null ) {
763 $this->fatalError( "\$IP not set, aborting!\n" .
764 '(Did you forget to call parent::__construct() in your maintenance script?)' );
767 # Make sure we can handle script parameters
768 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
769 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
772 // Send PHP warnings and errors to stderr instead of stdout.
773 // This aids in diagnosing problems, while keeping messages
774 // out of redirected output.
775 if ( ini_get( 'display_errors' ) ) {
776 ini_set( 'display_errors', 'stderr' );
779 $this->loadParamsAndArgs();
781 # Set the memory limit
782 # Note we need to set it again later in cache LocalSettings changed it
783 $this->adjustMemoryLimit();
785 # Set max execution time to 0 (no limit). PHP.net says that
786 # "When running PHP from the command line the default setting is 0."
787 # But sometimes this doesn't seem to be the case.
788 ini_set( 'max_execution_time', 0 );
790 # Define us as being in MediaWiki
791 define( 'MEDIAWIKI', true );
793 $wgCommandLineMode = true;
795 # Turn off output buffering if it's on
796 while ( ob_get_level() > 0 ) {
802 * Normally we disable the memory_limit when running admin scripts.
803 * Some scripts may wish to actually set a limit, however, to avoid
804 * blowing up unexpectedly. We also support a --memory-limit option,
805 * to allow sysadmins to explicitly set one if they'd prefer to override
806 * defaults (or for people using Suhosin which yells at you for trying
807 * to disable the limits)
810 public function memoryLimit() {
811 $limit = $this->getOption( 'memory-limit', 'max' );
812 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
817 * Adjusts PHP's memory limit to better suit our needs, if needed.
819 protected function adjustMemoryLimit() {
820 $limit = $this->memoryLimit();
821 if ( $limit == 'max' ) {
822 $limit = -1; // no memory limit
824 if ( $limit != 'default' ) {
825 ini_set( 'memory_limit', $limit );
830 * Activate the profiler (assuming $wgProfiler is set)
832 protected function activateProfiler() {
833 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
835 $output = $this->getOption( 'profiler' );
840 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
841 $class = $wgProfiler['class'];
842 /** @var Profiler $profiler */
843 $profiler = new $class(
844 [ 'sampling' => 1, 'output' => [ $output ] ]
846 +
[ 'threshold' => $wgProfileLimit ]
848 $profiler->setAllowOutput();
849 Profiler
::replaceStubInstance( $profiler );
852 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
853 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
854 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
858 * Clear all params and arguments.
860 public function clearParamsAndArgs() {
861 $this->mOptions
= [];
863 $this->mInputLoaded
= false;
867 * Load params and arguments from a given array
868 * of command-line arguments
873 public function loadWithArgv( $argv ) {
876 $this->orderedOptions
= [];
879 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
880 if ( $arg == '--' ) {
881 # End of options, remainder should be considered arguments
882 $arg = next( $argv );
883 while ( $arg !== false ) {
885 $arg = next( $argv );
888 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
890 $option = substr( $arg, 2 );
891 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
892 $param = next( $argv );
893 if ( $param === false ) {
894 $this->error( "\nERROR: $option parameter needs a value after it\n" );
895 $this->maybeHelp( true );
898 $this->setParam( $options, $option, $param );
900 $bits = explode( '=', $option, 2 );
901 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
903 } elseif ( $arg == '-' ) {
904 # Lonely "-", often used to indicate stdin or stdout.
906 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
908 $argLength = strlen( $arg );
909 for ( $p = 1; $p < $argLength; $p++
) {
911 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
912 $option = $this->mShortParamsMap
[$option];
915 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
916 $param = next( $argv );
917 if ( $param === false ) {
918 $this->error( "\nERROR: $option parameter needs a value after it\n" );
919 $this->maybeHelp( true );
921 $this->setParam( $options, $option, $param );
923 $this->setParam( $options, $option, 1 );
931 $this->mOptions
= $options;
932 $this->mArgs
= $args;
933 $this->loadSpecialVars();
934 $this->mInputLoaded
= true;
938 * Helper function used solely by loadParamsAndArgs
939 * to prevent code duplication
941 * This sets the param in the options array based on
942 * whether or not it can be specified multiple times.
945 * @param array $options
946 * @param string $option
947 * @param mixed $value
949 private function setParam( &$options, $option, $value ) {
950 $this->orderedOptions
[] = [ $option, $value ];
952 if ( isset( $this->mParams
[$option] ) ) {
953 $multi = $this->mParams
[$option]['multiOccurrence'];
957 $exists = array_key_exists( $option, $options );
958 if ( $multi && $exists ) {
959 $options[$option][] = $value;
960 } elseif ( $multi ) {
961 $options[$option] = [ $value ];
962 } elseif ( !$exists ) {
963 $options[$option] = $value;
965 $this->error( "\nERROR: $option parameter given twice\n" );
966 $this->maybeHelp( true );
971 * Process command line arguments
972 * $mOptions becomes an array with keys set to the option names
973 * $mArgs becomes a zero-based array containing the non-option arguments
975 * @param string|null $self The name of the script, if any
976 * @param array|null $opts An array of options, in form of key=>value
977 * @param array|null $args An array of command line arguments
979 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
980 # If we were given opts or args, set those and return early
982 $this->mSelf
= $self;
983 $this->mInputLoaded
= true;
986 $this->mOptions
= $opts;
987 $this->mInputLoaded
= true;
990 $this->mArgs
= $args;
991 $this->mInputLoaded
= true;
994 # If we've already loaded input (either by user values or from $argv)
995 # skip on loading it again. The array_shift() will corrupt values if
996 # it's run again and again
997 if ( $this->mInputLoaded
) {
998 $this->loadSpecialVars();
1004 $this->mSelf
= $argv[0];
1005 $this->loadWithArgv( array_slice( $argv, 1 ) );
1009 * Run some validation checks on the params, etc
1011 public function validateParamsAndArgs() {
1013 # Check to make sure we've got all the required options
1014 foreach ( $this->mParams
as $opt => $info ) {
1015 if ( $info['require'] && !$this->hasOption( $opt ) ) {
1016 $this->error( "Param $opt required!" );
1020 # Check arg list too
1021 foreach ( $this->mArgList
as $k => $info ) {
1022 if ( $info['require'] && !$this->hasArg( $k ) ) {
1023 $this->error( 'Argument <' . $info['name'] . '> required!' );
1027 if ( !$this->mAllowUnregisteredOptions
) {
1028 # Check for unexpected options
1029 foreach ( $this->mOptions
as $opt => $val ) {
1030 if ( !$this->supportsOption( $opt ) ) {
1031 $this->error( "Unexpected option $opt!" );
1037 $this->maybeHelp( $die );
1041 * Handle the special variables that are global to all scripts
1043 protected function loadSpecialVars() {
1044 if ( $this->hasOption( 'dbuser' ) ) {
1045 $this->mDbUser
= $this->getOption( 'dbuser' );
1047 if ( $this->hasOption( 'dbpass' ) ) {
1048 $this->mDbPass
= $this->getOption( 'dbpass' );
1050 if ( $this->hasOption( 'quiet' ) ) {
1051 $this->mQuiet
= true;
1053 if ( $this->hasOption( 'batch-size' ) ) {
1054 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1059 * Maybe show the help.
1060 * @param bool $force Whether to force the help to show, default false
1062 protected function maybeHelp( $force = false ) {
1063 if ( !$force && !$this->hasOption( 'help' ) ) {
1067 $screenWidth = 80; // TODO: Calculate this!
1069 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1071 ksort( $this->mParams
);
1072 $this->mQuiet
= false;
1075 if ( $this->mDescription
) {
1076 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1078 $output = "\nUsage: php " . basename( $this->mSelf
);
1080 // ... append parameters ...
1081 if ( $this->mParams
) {
1082 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1085 // ... and append arguments.
1086 if ( $this->mArgList
) {
1088 foreach ( $this->mArgList
as $k => $arg ) {
1089 if ( $arg['require'] ) {
1090 $output .= '<' . $arg['name'] . '>';
1092 $output .= '[' . $arg['name'] . ']';
1094 if ( $k < count( $this->mArgList
) - 1 ) {
1099 $this->output( "$output\n\n" );
1101 # TODO abstract some repetitive code below
1103 // Generic parameters
1104 $this->output( "Generic maintenance parameters:\n" );
1105 foreach ( $this->mGenericParameters
as $par => $info ) {
1106 if ( $info['shortName'] !== false ) {
1107 $par .= " (-{$info['shortName']})";
1110 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1111 "\n$tab$tab" ) . "\n"
1114 $this->output( "\n" );
1116 $scriptDependantParams = $this->mDependantParameters
;
1117 if ( count( $scriptDependantParams ) > 0 ) {
1118 $this->output( "Script dependant parameters:\n" );
1119 // Parameters description
1120 foreach ( $scriptDependantParams as $par => $info ) {
1121 if ( $info['shortName'] !== false ) {
1122 $par .= " (-{$info['shortName']})";
1125 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1126 "\n$tab$tab" ) . "\n"
1129 $this->output( "\n" );
1132 // Script specific parameters not defined on construction by
1133 // Maintenance::addDefaultParams()
1134 $scriptSpecificParams = array_diff_key(
1135 # all script parameters:
1137 # remove the Maintenance default parameters:
1138 $this->mGenericParameters
,
1139 $this->mDependantParameters
1141 if ( count( $scriptSpecificParams ) > 0 ) {
1142 $this->output( "Script specific parameters:\n" );
1143 // Parameters description
1144 foreach ( $scriptSpecificParams as $par => $info ) {
1145 if ( $info['shortName'] !== false ) {
1146 $par .= " (-{$info['shortName']})";
1149 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1150 "\n$tab$tab" ) . "\n"
1153 $this->output( "\n" );
1157 if ( count( $this->mArgList
) > 0 ) {
1158 $this->output( "Arguments:\n" );
1159 // Arguments description
1160 foreach ( $this->mArgList
as $info ) {
1161 $openChar = $info['require'] ?
'<' : '[';
1162 $closeChar = $info['require'] ?
'>' : ']';
1164 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1165 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1168 $this->output( "\n" );
1175 * Handle some last-minute setup here.
1177 public function finalSetup() {
1178 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1179 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1180 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1182 # Turn off output buffering again, it might have been turned on in the settings files
1183 if ( ob_get_level() ) {
1187 $wgCommandLineMode = true;
1189 # Override $wgServer
1190 if ( $this->hasOption( 'server' ) ) {
1191 $wgServer = $this->getOption( 'server', $wgServer );
1194 # If these were passed, use them
1195 if ( $this->mDbUser
) {
1196 $wgDBadminuser = $this->mDbUser
;
1198 if ( $this->mDbPass
) {
1199 $wgDBadminpassword = $this->mDbPass
;
1201 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1202 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1204 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1207 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1208 $wgDBuser = $wgDBadminuser;
1209 $wgDBpassword = $wgDBadminpassword;
1211 if ( $wgDBservers ) {
1213 * @var array $wgDBservers
1215 foreach ( $wgDBservers as $i => $server ) {
1216 $wgDBservers[$i]['user'] = $wgDBuser;
1217 $wgDBservers[$i]['password'] = $wgDBpassword;
1220 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1221 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1222 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1224 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1227 # Apply debug settings
1228 if ( $this->hasOption( 'mwdebug' ) ) {
1229 require __DIR__
. '/../includes/DevelopmentSettings.php';
1232 // Per-script profiling; useful for debugging
1233 $this->activateProfiler();
1235 $this->afterFinalSetup();
1237 $wgShowExceptionDetails = true;
1238 $wgShowHostnames = true;
1240 Wikimedia\
suppressWarnings();
1241 set_time_limit( 0 );
1242 Wikimedia\restoreWarnings
();
1244 $this->adjustMemoryLimit();
1248 * Execute a callback function at the end of initialisation
1250 protected function afterFinalSetup() {
1251 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1252 // @phan-suppress-next-line PhanUndeclaredConstant
1253 call_user_func( MW_CMDLINE_CALLBACK
);
1258 * Potentially debug globals. Originally a feature only
1261 public function globals() {
1262 if ( $this->hasOption( 'globals' ) ) {
1263 print_r( $GLOBALS );
1268 * Generic setup for most installs. Returns the location of LocalSettings
1271 public function loadSettings() {
1272 global $wgCommandLineMode, $IP;
1274 if ( isset( $this->mOptions
['conf'] ) ) {
1275 $settingsFile = $this->mOptions
['conf'];
1276 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1277 $settingsFile = MW_CONFIG_FILE
;
1279 $settingsFile = "$IP/LocalSettings.php";
1281 if ( isset( $this->mOptions
['wiki'] ) ) {
1282 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1283 define( 'MW_DB', $bits[0] );
1284 define( 'MW_PREFIX', $bits[1] ??
'' );
1285 } elseif ( isset( $this->mOptions
['server'] ) ) {
1286 // Provide the option for site admins to detect and configure
1287 // multiple wikis based on server names. This offers --server
1288 // as alternative to --wiki.
1289 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1290 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1293 if ( !is_readable( $settingsFile ) ) {
1294 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1295 "must exist and be readable in the source directory.\n" .
1296 "Use --conf to specify it." );
1298 $wgCommandLineMode = true;
1300 return $settingsFile;
1304 * Support function for cleaning up redundant text records
1305 * @param bool $delete Whether or not to actually delete the records
1306 * @author Rob Church <robchur@gmail.com>
1308 public function purgeRedundantText( $delete = true ) {
1309 global $wgMultiContentRevisionSchemaMigrationStage;
1311 # Data should come off the master, wrapped in a transaction
1312 $dbw = $this->getDB( DB_MASTER
);
1313 $this->beginTransaction( $dbw, __METHOD__
);
1315 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1316 # Get "active" text records from the revisions table
1318 $this->output( 'Searching for active text records in revisions table...' );
1319 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1320 foreach ( $res as $row ) {
1321 $cur[] = $row->rev_text_id
;
1323 $this->output( "done.\n" );
1325 # Get "active" text records from the archive table
1326 $this->output( 'Searching for active text records in archive table...' );
1327 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1328 foreach ( $res as $row ) {
1329 # old pre-MW 1.5 records can have null ar_text_id's.
1330 if ( $row->ar_text_id
!== null ) {
1331 $cur[] = $row->ar_text_id
;
1334 $this->output( "done.\n" );
1336 # Get "active" text records via the content table
1338 $this->output( 'Searching for active text records via contents table...' );
1339 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1340 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1341 foreach ( $res as $row ) {
1342 // @phan-suppress-next-line PhanUndeclaredMethod
1343 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1348 $this->output( "done.\n" );
1350 $this->output( "done.\n" );
1352 # Get the IDs of all text records not in these sets
1353 $this->output( 'Searching for inactive text records...' );
1354 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1355 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1357 foreach ( $res as $row ) {
1358 $old[] = $row->old_id
;
1360 $this->output( "done.\n" );
1362 # Inform the user of what we're going to do
1363 $count = count( $old );
1364 $this->output( "$count inactive items found.\n" );
1366 # Delete as appropriate
1367 if ( $delete && $count ) {
1368 $this->output( 'Deleting...' );
1369 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1370 $this->output( "done.\n" );
1373 $this->commitTransaction( $dbw, __METHOD__
);
1377 * Get the maintenance directory.
1380 protected function getDir() {
1385 * Returns a database to be used by current maintenance script.
1387 * This uses the main LBFactory instance by default unless overriden via setDB().
1389 * This function has the same parameters as LoadBalancer::getConnection().
1391 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1392 * @param string|string[] $groups default: empty array
1393 * @param string|bool $dbDomain default: current wiki
1394 * @return IMaintainableDatabase
1396 protected function getDB( $db, $groups = [], $dbDomain = false ) {
1397 if ( $this->mDb
=== null ) {
1398 return MediaWikiServices
::getInstance()
1399 ->getDBLoadBalancerFactory()
1400 ->getMainLB( $dbDomain )
1401 ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1408 * Sets database object to be returned by getDB().
1410 * @param IMaintainableDatabase $db
1412 public function setDB( IMaintainableDatabase
$db ) {
1417 * Begin a transcation on a DB
1419 * This method makes it clear that begin() is called from a maintenance script,
1420 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1422 * @param IDatabase $dbw
1423 * @param string $fname Caller name
1426 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1427 $dbw->begin( $fname );
1431 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1433 * This method makes it clear that commit() is called from a maintenance script,
1434 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1436 * @param IDatabase $dbw
1437 * @param string $fname Caller name
1438 * @return bool Whether the replica DB wait succeeded
1441 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1442 $dbw->commit( $fname );
1443 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1444 $waitSucceeded = $lbFactory->waitForReplication(
1445 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1447 $this->lastReplicationWait
= microtime( true );
1448 return $waitSucceeded;
1452 * Rollback the transcation on a DB handle
1454 * This method makes it clear that rollback() is called from a maintenance script,
1455 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1457 * @param IDatabase $dbw
1458 * @param string $fname Caller name
1461 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1462 $dbw->rollback( $fname );
1466 * Lock the search index
1467 * @param IMaintainableDatabase &$db
1469 private function lockSearchindex( $db ) {
1470 $write = [ 'searchindex' ];
1480 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1485 * @param IMaintainableDatabase &$db
1487 private function unlockSearchindex( $db ) {
1488 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1492 * Unlock and lock again
1493 * Since the lock is low-priority, queued reads will be able to complete
1494 * @param IMaintainableDatabase &$db
1496 private function relockSearchindex( $db ) {
1497 $this->unlockSearchindex( $db );
1498 $this->lockSearchindex( $db );
1502 * Perform a search index update with locking
1503 * @param int $maxLockTime The maximum time to keep the search index locked.
1504 * @param callable $callback The function that will update the function.
1505 * @param IMaintainableDatabase $dbw
1506 * @param array|IResultWrapper $results
1508 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1512 if ( $maxLockTime ) {
1513 $this->output( " --- Waiting for lock ---" );
1514 $this->lockSearchindex( $dbw );
1516 $this->output( "\n" );
1519 # Loop through the results and do a search update
1520 foreach ( $results as $row ) {
1521 # Allow reads to be processed
1522 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1523 $this->output( " --- Relocking ---" );
1524 $this->relockSearchindex( $dbw );
1526 $this->output( "\n" );
1528 call_user_func( $callback, $dbw, $row );
1531 # Unlock searchindex
1532 if ( $maxLockTime ) {
1533 $this->output( " --- Unlocking --" );
1534 $this->unlockSearchindex( $dbw );
1535 $this->output( "\n" );
1540 * Update the searchindex table for a given pageid
1541 * @param IDatabase $dbw A database write handle
1542 * @param int $pageId The page ID to update.
1543 * @return null|string
1545 public function updateSearchIndexForPage( $dbw, $pageId ) {
1546 // Get current revision
1547 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1550 $titleObj = $rev->getTitle();
1551 $title = $titleObj->getPrefixedDBkey();
1552 $this->output( "$title..." );
1553 # Update searchindex
1554 $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent() );
1556 $this->output( "\n" );
1563 * Count down from $seconds to zero on the terminal, with a one-second pause
1564 * between showing each number. If the maintenance script is in quiet mode,
1565 * this function does nothing.
1569 * @codeCoverageIgnore
1570 * @param int $seconds
1572 protected function countDown( $seconds ) {
1573 if ( $this->isQuiet() ) {
1576 for ( $i = $seconds; $i >= 0; $i-- ) {
1577 if ( $i != $seconds ) {
1578 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1580 $this->output( $i );
1585 $this->output( "\n" );
1589 * Wrapper for posix_isatty()
1590 * We default as considering stdin a tty (for nice readline methods)
1591 * but treating stout as not a tty to avoid color codes
1593 * @param mixed $fd File descriptor
1596 public static function posix_isatty( $fd ) {
1597 if ( !function_exists( 'posix_isatty' ) ) {
1600 return posix_isatty( $fd );
1605 * Prompt the console for input
1606 * @param string $prompt What to begin the line with, like '> '
1607 * @return string Response
1609 public static function readconsole( $prompt = '> ' ) {
1610 static $isatty = null;
1611 if ( is_null( $isatty ) ) {
1612 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1615 if ( $isatty && function_exists( 'readline' ) ) {
1616 return readline( $prompt );
1619 $st = self
::readlineEmulation( $prompt );
1621 if ( feof( STDIN
) ) {
1624 $st = fgets( STDIN
, 1024 );
1627 if ( $st === false ) {
1630 $resp = trim( $st );
1637 * Emulate readline()
1638 * @param string $prompt What to begin the line with, like '> '
1641 private static function readlineEmulation( $prompt ) {
1642 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1643 if ( !wfIsWindows() && $bash ) {
1645 $encPrompt = Shell
::escape( $prompt );
1646 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1647 $encCommand = Shell
::escape( $command );
1648 $line = Shell
::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1650 if ( $retval == 0 ) {
1652 } elseif ( $retval == 127 ) {
1653 // Couldn't execute bash even though we thought we saw it.
1654 // Shell probably spit out an error message, sorry :(
1655 // Fall through to fgets()...
1662 // Fallback... we'll have no editing controls, EWWW
1663 if ( feof( STDIN
) ) {
1668 return fgets( STDIN
, 1024 );
1672 * Get the terminal size as a two-element array where the first element
1673 * is the width (number of columns) and the second element is the height
1678 public static function getTermSize() {
1679 $default = [ 80, 50 ];
1680 if ( wfIsWindows() ) {
1683 if ( Shell
::isDisabled() ) {
1686 // It's possible to get the screen size with VT-100 terminal escapes,
1687 // but reading the responses is not possible without setting raw mode
1688 // (unless you want to require the user to press enter), and that
1689 // requires an ioctl(), which we can't do. So we have to shell out to
1690 // something that can do the relevant syscalls. There are a few
1691 // options. Linux and Mac OS X both have "stty size" which does the
1693 $result = Shell
::command( 'stty', 'size' )
1695 if ( $result->getExitCode() !== 0 ) {
1698 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1701 return [ intval( $m[2] ), intval( $m[1] ) ];
1705 * Call this to set up the autoloader to allow classes to be used from the
1708 public static function requireTestsAutoloader() {
1709 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1714 * Fake maintenance wrapper, mostly used for the web installer/updater
1716 class FakeMaintenance
extends Maintenance
{
1717 protected $mSelf = "FakeMaintenanceScript";
1719 public function execute() {
1724 * Class for scripts that perform database maintenance and want to log the
1725 * update in `updatelog` so we can later skip it
1727 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1728 public function __construct() {
1729 parent
::__construct();
1730 $this->addOption( 'force', 'Run the update even if it was completed already' );
1731 $this->setBatchSize( 200 );
1734 public function execute() {
1735 $db = $this->getDB( DB_MASTER
);
1736 $key = $this->getUpdateKey();
1738 if ( !$this->hasOption( 'force' )
1739 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1741 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1746 if ( !$this->doDBUpdates() ) {
1750 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, [ 'IGNORE' ] );
1756 * Message to show that the update was done already and was just skipped
1759 protected function updateSkippedMessage() {
1760 $key = $this->getUpdateKey();
1762 return "Update '{$key}' already logged as completed. Use --force to run it again.";
1766 * Do the actual work. All child classes will need to implement this.
1767 * Return true to log the update as done or false (usually on failure).
1770 abstract protected function doDBUpdates();
1773 * Get the update key name to go in the update log table
1776 abstract protected function getUpdateKey();