Add partial support for running Parsoid selser tests
[mediawiki.git] / maintenance / rebuildLocalisationCache.php
blob1bf63334e5f0ff59716dc00e17039a6a9c518cda
1 <?php
3 /**
4 * Rebuild the localisation cache. Useful if you disabled automatic updates
5 * using $wgLocalisationCacheConf['manualRecache'] = true;
7 * Usage:
8 * php rebuildLocalisationCache.php [--force] [--threads=N]
10 * Use --force to rebuild all files, even the ones that are not out of date.
11 * Use --threads=N to fork more threads.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
28 * @file
29 * @ingroup Maintenance
32 use MediaWiki\Config\ServiceOptions;
33 use MediaWiki\Languages\LanguageNameUtils;
34 use MediaWiki\Logger\LoggerFactory;
35 use MediaWiki\MediaWikiServices;
36 use MediaWiki\Settings\SettingsBuilder;
38 require_once __DIR__ . '/Maintenance.php';
40 /**
41 * Maintenance script to rebuild the localisation cache.
43 * @ingroup Maintenance
45 class RebuildLocalisationCache extends Maintenance {
46 public function __construct() {
47 parent::__construct();
48 $this->addDescription( 'Rebuild the localisation cache' );
49 $this->addOption( 'force', 'Rebuild all files, even ones not out of date' );
50 $this->addOption( 'threads', 'Fork more than one thread', false, true );
51 $this->addOption( 'outdir', 'Override the output directory (normally $wgCacheDirectory)',
52 false, true );
53 $this->addOption( 'lang', 'Only rebuild these languages, comma separated.',
54 false, true );
55 $this->addOption(
56 'store-class',
57 'Override the LC store class (normally $wgLocalisationCacheConf[\'storeClass\'])',
58 false,
59 true
61 $this->addOption(
62 'no-database',
63 'EXPERIMENTAL: Disable the database backend. Setting this option will result in an error ' .
64 'if you have extensions or use site configuration that need the database. This is an ' .
65 'experimental feature to allow offline building of the localisation cache. Known limitations:' .
66 "\n" .
67 '* Incompatible with LCStoreDB, which always requires a database. ' . "\n" .
68 '* The message purge may require a database. See --skip-message-purge.'
70 // T237148: The Gadget extension (bundled with MediaWiki by default) requires a database`
71 // connection to register its modules for MessageBlobStore.
72 $this->addOption(
73 'skip-message-purge',
74 'Skip purging of MessageBlobStore. The purge operation may require a database, depending ' .
75 'on the configuration and extensions on this wiki. If skipping the purge now, you need to ' .
76 'run purgeMessageBlobStore.php shortly after deployment.'
78 $this->addOption(
79 'no-progress',
80 "Don't print a message for each rebuilt language file. Use this instead of " .
81 "--quiet to get a brief summary of the operation."
85 public function finalSetup( SettingsBuilder $settingsBuilder = null ) {
86 # This script needs to be run to build the initial l10n cache. But if
87 # LanguageCode is not 'en', it won't be able to run because there is
88 # no l10n cache. Break the cycle by forcing the LanguageCode setting to 'en'.
89 $settingsBuilder->putConfigValue( 'LanguageCode', 'en' );
90 parent::finalSetup( $settingsBuilder );
93 public function execute() {
94 global $wgLocalisationCacheConf, $wgCacheDirectory;
96 $force = $this->hasOption( 'force' );
97 $threads = $this->getOption( 'threads', 1 );
98 if ( $threads < 1 || $threads != intval( $threads ) ) {
99 $this->output( "Invalid thread count specified; running single-threaded.\n" );
100 $threads = 1;
102 if ( $threads > 1 && wfIsWindows() ) {
103 $this->output( "Threaded rebuild is not supported on Windows; running single-threaded.\n" );
104 $threads = 1;
106 if ( $threads > 1 && ( !extension_loaded( 'sockets' ) || !function_exists( 'pcntl_fork' ) ) ) {
107 $this->output( "Threaded rebuild requires ext-pcntl and ext-sockets; running single-threaded.\n" );
108 $threads = 1;
111 $conf = $wgLocalisationCacheConf;
112 // Allow fallbacks to create CDB files
113 $conf['manualRecache'] = false;
114 $conf['forceRecache'] = $force || !empty( $conf['forceRecache'] );
115 if ( $this->hasOption( 'outdir' ) ) {
116 $conf['storeDirectory'] = $this->getOption( 'outdir' );
119 if ( $this->hasOption( 'store-class' ) ) {
120 $conf['storeClass'] = $this->getOption( 'store-class' );
123 // XXX Copy-pasted from ServiceWiring.php. Do we need a factory for this one caller?
124 $services = MediaWikiServices::getInstance();
125 $lc = new LocalisationCacheBulkLoad(
126 new ServiceOptions(
127 LocalisationCache::CONSTRUCTOR_OPTIONS,
128 $conf,
129 $services->getMainConfig()
131 LocalisationCache::getStoreFromConf( $conf, $wgCacheDirectory ),
132 LoggerFactory::getInstance( 'localisation' ),
133 $this->hasOption( 'skip-message-purge' ) ? [] :
134 [ static function () use ( $services ) {
135 MessageBlobStore::clearGlobalCacheEntry( $services->getMainWANObjectCache() );
136 } ],
137 $services->getLanguageNameUtils(),
138 $services->getHookContainer()
141 $allCodes = array_keys( $services
142 ->getLanguageNameUtils()
143 ->getLanguageNames( LanguageNameUtils::AUTONYMS, LanguageNameUtils::SUPPORTED ) );
144 if ( $this->hasOption( 'lang' ) ) {
145 # Validate requested languages
146 $codes = array_intersect( $allCodes,
147 explode( ',', $this->getOption( 'lang' ) ) );
148 # Bailed out if nothing is left
149 if ( count( $codes ) == 0 ) {
150 $this->fatalError( 'None of the languages specified exists.' );
152 } else {
153 # By default get all languages
154 $codes = $allCodes;
156 sort( $codes );
158 $numRebuilt = 0;
159 $total = count( $codes );
160 $parentStatus = 0;
162 if ( $threads <= 1 ) {
163 // Single-threaded implementation
164 $numRebuilt += $this->doRebuild( $codes, $lc, $force );
165 } else {
166 // Multi-threaded implementation
167 $chunks = array_chunk( $codes, ceil( count( $codes ) / $threads ) );
168 // Map from PID to readable socket
169 $sockets = [];
171 foreach ( $chunks as $codes ) {
172 $socketpair = [];
173 // Create a pair of sockets so that the child can communicate
174 // the number of rebuilt langs to the parent.
175 if ( socket_create_pair( AF_UNIX, SOCK_STREAM, 0, $socketpair ) === false ) {
176 $this->fatalError( 'socket_create_pair failed' );
179 $pid = pcntl_fork();
181 if ( $pid === -1 ) {
182 $this->fatalError( ' pcntl_fork failed' );
183 } elseif ( $pid === 0 ) {
184 // Child, reseed because there is no bug in PHP:
185 // https://bugs.php.net/bug.php?id=42465
186 mt_srand( getmypid() );
188 $numRebuilt = $this->doRebuild( $codes, $lc, $force );
189 // Report the number of rebuilt langs to the parent.
190 $msg = strval( $numRebuilt ) . "\n";
191 socket_write( $socketpair[1], $msg, strlen( $msg ) );
192 // Child exits.
193 return;
194 } else {
195 // Main thread
196 $sockets[$pid] = $socketpair[0];
200 // Wait for all children
201 foreach ( $sockets as $pid => $socket ) {
202 $status = 0;
203 pcntl_waitpid( $pid, $status );
205 if ( pcntl_wifexited( $status ) ) {
206 $code = pcntl_wexitstatus( $status );
207 if ( $code ) {
208 $this->output( "Pid $pid exited with status $code !!\n" );
209 } else {
210 // Good exit status from child. Read the number of rebuilt langs from it.
211 $res = socket_read( $socket, 512, PHP_NORMAL_READ );
212 if ( $res === false ) {
213 $this->output( "socket_read failed in parent\n" );
214 } else {
215 $numRebuilt += intval( $res );
219 // Mush all child statuses into a single value in the parent.
220 $parentStatus |= $code;
221 } elseif ( pcntl_wifsignaled( $status ) ) {
222 $signum = pcntl_wtermsig( $status );
223 $this->output( "Pid $pid terminated by signal $signum !!\n" );
224 $parentStatus |= 1;
229 $this->output( "$numRebuilt languages rebuilt out of $total\n" );
230 if ( $numRebuilt === 0 ) {
231 $this->output( "Use --force to rebuild the caches which are still fresh.\n" );
233 if ( $parentStatus ) {
234 $this->fatalError( 'Failed.', $parentStatus );
239 * Helper function to rebuild list of languages codes. Prints the code
240 * for each language which is rebuilt.
241 * @param string[] $codes List of language codes to rebuild.
242 * @param LocalisationCache $lc
243 * @param bool $force Rebuild up-to-date languages
244 * @return int Number of rebuilt languages
246 private function doRebuild( $codes, $lc, $force ) {
247 $numRebuilt = 0;
248 foreach ( $codes as $code ) {
249 if ( $force || $lc->isExpired( $code ) ) {
250 if ( !$this->hasOption( 'no-progress' ) ) {
251 $this->output( "Rebuilding $code...\n" );
253 $lc->recache( $code );
254 $numRebuilt++;
258 return $numRebuilt;
261 /** @inheritDoc */
262 public function getDbType() {
263 if ( $this->hasOption( 'no-database' ) ) {
264 return Maintenance::DB_NONE;
267 return parent::getDbType();
271 * Sets whether a run of this maintenance script has the force parameter set
273 * @param bool $forced
275 public function setForce( $forced = true ) {
276 $this->mOptions['force'] = $forced;
280 $maintClass = RebuildLocalisationCache::class;
281 require_once RUN_MAINTENANCE_IF_MAIN;