MediaWiki master
rebuildLocalisationCache.php
Go to the documentation of this file.
1<?php
2
19use MediaWiki\Languages\LanguageNameUtils;
25
26// @codeCoverageIgnoreStart
27require_once __DIR__ . '/Maintenance.php';
28// @codeCoverageIgnoreEnd
29
36 public function __construct() {
37 parent::__construct();
38 $this->addDescription( 'Rebuild the localisation cache' );
39 $this->addOption( 'dry-run', 'Determine what languages need to be rebuilt without changing anything' );
40 $this->addOption( 'force', 'Rebuild all files, even ones not out of date' );
41 $this->addOption( 'threads', 'Fork more than one thread', false, true );
42 $this->addOption( 'outdir', 'Override the output directory (normally $wgCacheDirectory)',
43 false, true );
44 $this->addOption( 'lang', 'Only rebuild these languages, comma separated.',
45 false, true );
46 $this->addOption(
47 'store-class',
48 'Override the LC store class (normally $wgLocalisationCacheConf[\'storeClass\'])',
49 false,
50 true
51 );
52 $this->addOption(
53 'no-database',
54 'EXPERIMENTAL: Disable the database backend. Setting this option will result in an error ' .
55 'if you have extensions or use site configuration that need the database. This is an ' .
56 'experimental feature to allow offline building of the localisation cache. Known limitations:' .
57 "\n" .
58 '* Incompatible with LCStoreDB, which always requires a database. ' . "\n" .
59 '* The message purge may require a database. See --skip-message-purge.'
60 );
61 // T237148: The Gadget extension (bundled with MediaWiki by default) requires a database`
62 // connection to register its modules for MessageBlobStore.
63 $this->addOption(
64 'skip-message-purge',
65 'Skip purging of MessageBlobStore. The purge operation may require a database, depending ' .
66 'on the configuration and extensions on this wiki. If skipping the purge now, you need to ' .
67 'run purgeMessageBlobStore.php shortly after deployment.'
68 );
69 $this->addOption(
70 'no-progress',
71 "Don't print a message for each rebuilt language file. Use this instead of " .
72 "--quiet to get a brief summary of the operation."
73 );
74 }
75
76 public function finalSetup( SettingsBuilder $settingsBuilder ) {
77 # This script needs to be run to build the initial l10n cache. But if
78 # LanguageCode is not 'en', it won't be able to run because there is
79 # no l10n cache. Break the cycle by forcing the LanguageCode setting to 'en'.
80 $settingsBuilder->putConfigValue( MainConfigNames::LanguageCode, 'en' );
81 parent::finalSetup( $settingsBuilder );
82 }
83
84 public function execute() {
85 $force = $this->hasOption( 'force' );
86 $threads = $this->getOption( 'threads', 1 );
87 if ( $threads < 1 || $threads != intval( $threads ) ) {
88 $this->output( "Invalid thread count specified; running single-threaded.\n" );
89 $threads = 1;
90 }
91 if ( $threads > 1 && wfIsWindows() ) {
92 $this->output( "Threaded rebuild is not supported on Windows; running single-threaded.\n" );
93 $threads = 1;
94 }
95 if ( $threads > 1 && ( !extension_loaded( 'sockets' ) || !function_exists( 'pcntl_fork' ) ) ) {
96 $this->output( "Threaded rebuild requires ext-pcntl and ext-sockets; running single-threaded.\n" );
97 $threads = 1;
98 }
99
100 $conf = $this->getConfig()->get( MainConfigNames::LocalisationCacheConf );
101 // Allow fallbacks to create CDB files
102 $conf['manualRecache'] = false;
103 $conf['forceRecache'] = $force || !empty( $conf['forceRecache'] );
104 if ( $this->hasOption( 'outdir' ) ) {
105 $conf['storeDirectory'] = $this->getOption( 'outdir' );
106 }
107
108 if ( $this->hasOption( 'store-class' ) ) {
109 $conf['storeClass'] = $this->getOption( 'store-class' );
110 }
111
112 // XXX Copy-pasted from ServiceWiring.php. Do we need a factory for this one caller?
113 $services = $this->getServiceContainer();
115 new ServiceOptions(
116 LocalisationCache::CONSTRUCTOR_OPTIONS,
117 $conf,
118 $services->getMainConfig()
119 ),
120 LocalisationCache::getStoreFromConf( $conf, $this->getConfig()->get( MainConfigNames::CacheDirectory ) ),
121 LoggerFactory::getInstance( 'localisation' ),
122 $this->hasOption( 'skip-message-purge' ) ? [] :
123 [ static function () use ( $services ) {
124 MessageBlobStore::clearGlobalCacheEntry( $services->getMainWANObjectCache() );
125 } ],
126 $services->getLanguageNameUtils(),
127 $services->getHookContainer()
128 );
129
130 $allCodes = array_keys( $services
131 ->getLanguageNameUtils()
132 ->getLanguageNames( LanguageNameUtils::AUTONYMS, LanguageNameUtils::SUPPORTED ) );
133 if ( $this->hasOption( 'lang' ) ) {
134 # Validate requested languages
135 $codes = array_intersect( $allCodes,
136 explode( ',', $this->getOption( 'lang' ) ) );
137 # Bailed out if nothing is left
138 if ( count( $codes ) == 0 ) {
139 $this->fatalError( 'None of the languages specified exists.' );
140 }
141 } else {
142 # By default get all languages
143 $codes = $allCodes;
144 }
145 sort( $codes );
146
147 $numRebuilt = 0;
148 $total = count( $codes );
149 $parentStatus = 0;
150
151 if ( $threads <= 1 ) {
152 // Single-threaded implementation
153 $numRebuilt += $this->doRebuild( $codes, $lc, $force );
154 } else {
155 // Multi-threaded implementation
156 $chunks = array_chunk( $codes, ceil( count( $codes ) / $threads ) );
157 // Map from PID to readable socket
158 $sockets = [];
159
160 foreach ( $chunks as $codes ) {
161 $socketpair = [];
162 // Create a pair of sockets so that the child can communicate
163 // the number of rebuilt langs to the parent.
164 if ( !socket_create_pair( AF_UNIX, SOCK_STREAM, 0, $socketpair ) ) {
165 $this->fatalError( 'socket_create_pair failed' );
166 }
167
168 $pid = pcntl_fork();
169
170 if ( $pid === -1 ) {
171 $this->fatalError( ' pcntl_fork failed' );
172 } elseif ( $pid === 0 ) {
173 // Child, reseed because there is no bug in PHP:
174 // https://bugs.php.net/bug.php?id=42465
175 mt_srand( getmypid() );
176
177 $numRebuilt = $this->doRebuild( $codes, $lc, $force );
178 // Report the number of rebuilt langs to the parent.
179 $msg = "$numRebuilt\n";
180 socket_write( $socketpair[1], $msg, strlen( $msg ) );
181 // Child exits.
182 return;
183 } else {
184 // Main thread
185 $sockets[$pid] = $socketpair[0];
186 }
187 }
188
189 // Wait for all children
190 foreach ( $sockets as $pid => $socket ) {
191 $status = 0;
192 pcntl_waitpid( $pid, $status );
193
194 if ( pcntl_wifexited( $status ) ) {
195 $code = pcntl_wexitstatus( $status );
196 if ( $code ) {
197 $this->output( "Pid $pid exited with status $code !!\n" );
198 } else {
199 // Good exit status from child. Read the number of rebuilt langs from it.
200 $res = socket_read( $socket, 512, PHP_NORMAL_READ );
201 if ( $res === false ) {
202 $this->output( "socket_read failed in parent\n" );
203 } else {
204 $numRebuilt += intval( $res );
205 }
206 }
207
208 // Mush all child statuses into a single value in the parent.
209 $parentStatus |= $code;
210 } elseif ( pcntl_wifsignaled( $status ) ) {
211 $signum = pcntl_wtermsig( $status );
212 $this->output( "Pid $pid terminated by signal $signum !!\n" );
213 $parentStatus |= 1;
214 }
215 }
216 }
217
218 $this->output( "$numRebuilt languages rebuilt out of $total\n" );
219 if ( $numRebuilt === 0 ) {
220 $this->output( "Use --force to rebuild the caches which are still fresh.\n" );
221 }
222 if ( $parentStatus ) {
223 $this->fatalError( 'Failed.', $parentStatus );
224 }
225 }
226
235 private function doRebuild( $codes, $lc, $force ) {
236 $numRebuilt = 0;
237 $operation = $this->hasOption( 'dry-run' ) ? "Would rebuild" : "Rebuilding";
238
239 foreach ( $codes as $code ) {
240 if ( $force || $lc->isExpired( $code ) ) {
241 if ( !$this->hasOption( 'no-progress' ) ) {
242 $this->output( "$operation $code...\n" );
243 }
244 if ( !$this->hasOption( 'dry-run' ) ) {
245 $lc->recache( $code );
246 }
247 $numRebuilt++;
248 }
249 }
250
251 return $numRebuilt;
252 }
253
255 public function getDbType() {
256 if ( $this->hasOption( 'no-database' ) ) {
257 return Maintenance::DB_NONE;
258 }
259
260 return parent::getDbType();
261 }
262
268 public function setForce( $forced = true ) {
269 $this->setOption( 'force', $forced );
270 }
271}
272
273// @codeCoverageIgnoreStart
274$maintClass = RebuildLocalisationCache::class;
275require_once RUN_MAINTENANCE_IF_MAIN;
276// @codeCoverageIgnoreEnd
wfIsWindows()
Check if the operating system is Windows.
LocalisationCache optimised for loading many languages at once.
A class for passing options to services.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
setOption(string $name, $value)
Programmatically set the value of the given option.
getOption( $name, $default=null)
Get an option, or return the default.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
This class generates message blobs for use by ResourceLoader.
Builder class for constructing a Config object from a set of sources during bootstrap.
putConfigValue(string $key, $value)
Puts a value into a config variable.
Maintenance script to rebuild the localisation cache.
finalSetup(SettingsBuilder $settingsBuilder)
Handle some last-minute setup here.
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
setForce( $forced=true)
Sets whether a run of this maintenance script has the force parameter set.