Merge "filerepo: rename resolveToStoragePath() and tweak file operation arrays"
[lhc/web/wiklou.git] / includes / db / MWLBFactory.php
1 <?php
2 /**
3 * Generator of database load balancing objects.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 use MediaWiki\Config\ServiceOptions;
25 use MediaWiki\Logger\LoggerFactory;
26 use Wikimedia\Rdbms\LBFactory;
27 use Wikimedia\Rdbms\DatabaseDomain;
28
29 /**
30 * MediaWiki-specific class for generating database load balancers
31 * @ingroup Database
32 */
33 abstract class MWLBFactory {
34
35 /** @var array Cache of already-logged deprecation messages */
36 private static $loggedDeprecations = [];
37
38 /**
39 * TODO Make this a const when HHVM support is dropped (T192166)
40 *
41 * @var array
42 * @since 1.34
43 */
44 public static $applyDefaultConfigOptions = [
45 'DBcompress',
46 'DBDefaultGroup',
47 'DBmwschema',
48 'DBname',
49 'DBpassword',
50 'DBport',
51 'DBprefix',
52 'DBserver',
53 'DBservers',
54 'DBssl',
55 'DBtype',
56 'DBuser',
57 'DBWindowsAuthentication',
58 'DebugDumpSql',
59 'DebugLogFile',
60 'ExternalServers',
61 'SQLiteDataDir',
62 'SQLMode',
63 ];
64
65 /**
66 * @param array $lbConf Config for LBFactory::__construct()
67 * @param ServiceOptions $options
68 * @param ConfiguredReadOnlyMode $readOnlyMode
69 * @param BagOStuff $srvCache
70 * @param BagOStuff $mainStash
71 * @param WANObjectCache $wanCache
72 * @return array
73 * @internal For use with service wiring
74 */
75 public static function applyDefaultConfig(
76 array $lbConf,
77 ServiceOptions $options,
78 ConfiguredReadOnlyMode $readOnlyMode,
79 BagOStuff $srvCache,
80 BagOStuff $mainStash,
81 WANObjectCache $wanCache
82 ) {
83 $options->assertRequiredOptions( self::$applyDefaultConfigOptions );
84
85 global $wgCommandLineMode;
86
87 $typesWithSchema = self::getDbTypesWithSchemas();
88
89 $lbConf += [
90 'localDomain' => new DatabaseDomain(
91 $options->get( 'DBname' ),
92 $options->get( 'DBmwschema' ),
93 $options->get( 'DBprefix' )
94 ),
95 'profiler' => function ( $section ) {
96 return Profiler::instance()->scopedProfileIn( $section );
97 },
98 'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
99 'replLogger' => LoggerFactory::getInstance( 'DBReplication' ),
100 'queryLogger' => LoggerFactory::getInstance( 'DBQuery' ),
101 'connLogger' => LoggerFactory::getInstance( 'DBConnection' ),
102 'perfLogger' => LoggerFactory::getInstance( 'DBPerformance' ),
103 'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
104 'deprecationLogger' => [ static::class, 'logDeprecation' ],
105 'cliMode' => $wgCommandLineMode,
106 'hostname' => wfHostname(),
107 'readOnlyReason' => $readOnlyMode->getReason(),
108 'defaultGroup' => $options->get( 'DBDefaultGroup' ),
109 ];
110
111 $serversCheck = [];
112 // When making changes here, remember to also specify MediaWiki-specific options
113 // for Database classes in the relevant Installer subclass.
114 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
115 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
116 if ( isset( $lbConf['servers'] ) ) {
117 // Server array is already explicitly configured
118 } elseif ( is_array( $options->get( 'DBservers' ) ) ) {
119 $lbConf['servers'] = [];
120 foreach ( $options->get( 'DBservers' ) as $i => $server ) {
121 $lbConf['servers'][$i] = self::initServerInfo( $server, $options );
122 }
123 } else {
124 $server = self::initServerInfo(
125 [
126 'host' => $options->get( 'DBserver' ),
127 'user' => $options->get( 'DBuser' ),
128 'password' => $options->get( 'DBpassword' ),
129 'dbname' => $options->get( 'DBname' ),
130 'type' => $options->get( 'DBtype' ),
131 'load' => 1
132 ],
133 $options
134 );
135
136 $server['flags'] |= $options->get( 'DBssl' ) ? DBO_SSL : 0;
137 $server['flags'] |= $options->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
138
139 $lbConf['servers'] = [ $server ];
140 }
141 if ( !isset( $lbConf['externalClusters'] ) ) {
142 $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
143 }
144
145 $serversCheck = $lbConf['servers'];
146 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
147 if ( isset( $lbConf['serverTemplate'] ) ) {
148 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
149 $lbConf['serverTemplate']['schema'] = $options->get( 'DBmwschema' );
150 }
151 $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
152 }
153 $serversCheck = [ $lbConf['serverTemplate'] ] ?? [];
154 }
155
156 self::assertValidServerConfigs(
157 $serversCheck,
158 $options->get( 'DBname' ),
159 $options->get( 'DBprefix' )
160 );
161
162 $lbConf = self::injectObjectCaches( $lbConf, $srvCache, $mainStash, $wanCache );
163
164 return $lbConf;
165 }
166
167 /**
168 * @return array
169 */
170 private static function getDbTypesWithSchemas() {
171 return [ 'postgres' ];
172 }
173
174 /**
175 * @param array $server
176 * @param ServiceOptions $options
177 * @return array
178 */
179 private static function initServerInfo( array $server, ServiceOptions $options ) {
180 if ( $server['type'] === 'sqlite' ) {
181 $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
182 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
183 // See https://www.sqlite.org/lang_transaction.html
184 // See https://www.sqlite.org/lockingv3.html#shared_lock
185 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
186 $server += [
187 'dbDirectory' => $options->get( 'SQLiteDataDir' ),
188 'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
189 ];
190 } elseif ( $server['type'] === 'postgres' ) {
191 $server += [
192 'port' => $options->get( 'DBport' ),
193 // Work around the reserved word usage in MediaWiki schema
194 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
195 ];
196 }
197
198 if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
199 $server += [ 'schema' => $options->get( 'DBmwschema' ) ];
200 }
201
202 $flags = DBO_DEFAULT;
203 $flags |= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG : 0;
204 $flags |= $options->get( 'DebugLogFile' ) ? DBO_DEBUG : 0;
205
206 $server += [
207 'tablePrefix' => $options->get( 'DBprefix' ),
208 'flags' => $flags,
209 'sqlMode' => $options->get( 'SQLMode' ),
210 ];
211
212 return $server;
213 }
214
215 /**
216 * @param array $lbConf
217 * @param BagOStuff $sCache
218 * @param BagOStuff $mStash
219 * @param WANObjectCache $wCache
220 * @return array
221 */
222 private static function injectObjectCaches(
223 array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
224 ) {
225 // Fallback if APC style caching is not an option
226 if ( $sCache instanceof EmptyBagOStuff ) {
227 $sCache = new HashBagOStuff( [ 'maxKeys' => 100 ] );
228 }
229
230 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
231 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
232 $lbConf['srvCache'] = $sCache;
233 }
234 if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
235 $lbConf['memStash'] = $mStash;
236 }
237 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
238 $lbConf['wanCache'] = $wCache;
239 }
240
241 return $lbConf;
242 }
243
244 /**
245 * @param array $servers
246 * @param string $ldDB Local domain database name
247 * @param string $ldTP Local domain prefix
248 */
249 private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
250 foreach ( $servers as $server ) {
251 $type = $server['type'] ?? null;
252 $srvDB = $server['dbname'] ?? null; // server DB
253 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
254
255 if ( $type === 'mysql' ) {
256 // A DB name is not needed to connect to mysql; 'dbname' is useless.
257 // This field only defines the DB to use for unspecified DB domains.
258 if ( $srvDB !== null && $srvDB !== $ldDB ) {
259 self::reportMismatchedDBs( $srvDB, $ldDB );
260 }
261 } elseif ( $type === 'postgres' ) {
262 if ( $srvTP !== '' ) {
263 self::reportIfPrefixSet( $srvTP, $type );
264 }
265 }
266
267 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
268 self::reportMismatchedPrefixes( $srvTP, $ldTP );
269 }
270 }
271 }
272
273 /**
274 * @param string $prefix Table prefix
275 * @param string $dbType Database type
276 */
277 private static function reportIfPrefixSet( $prefix, $dbType ) {
278 $e = new UnexpectedValueException(
279 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
280 "MediaWiki does not support using a table prefix with this RDBMS type."
281 );
282 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
283 exit;
284 }
285
286 /**
287 * @param string $srvDB Server config database
288 * @param string $ldDB Local DB domain database
289 */
290 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
291 $e = new UnexpectedValueException(
292 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
293 "Set \$wgDBname to the database used by this wiki project. " .
294 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
295 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
296 "use of Database::getDomainId(), and other features are not reliable when " .
297 "\$wgDBservers does not match the local wiki database/prefix."
298 );
299 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
300 exit;
301 }
302
303 /**
304 * @param string $srvTP Server config table prefix
305 * @param string $ldTP Local DB domain database
306 */
307 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
308 $e = new UnexpectedValueException(
309 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
310 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
311 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
312 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
313 "use of Database::getDomainId(), and other features are not reliable when " .
314 "\$wgDBservers does not match the local wiki database/prefix."
315 );
316 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
317 exit;
318 }
319
320 /**
321 * Returns the LBFactory class to use and the load balancer configuration.
322 *
323 * @todo instead of this, use a ServiceContainer for managing the different implementations.
324 *
325 * @param array $config (e.g. $wgLBFactoryConf)
326 * @return string Class name
327 * @internal For use with service wiring
328 */
329 public static function getLBFactoryClass( array $config ) {
330 // For configuration backward compatibility after removing
331 // underscores from class names in MediaWiki 1.23.
332 $bcClasses = [
333 'LBFactory_Simple' => 'LBFactorySimple',
334 'LBFactory_Single' => 'LBFactorySingle',
335 'LBFactory_Multi' => 'LBFactoryMulti'
336 ];
337
338 $class = $config['class'];
339
340 if ( isset( $bcClasses[$class] ) ) {
341 $class = $bcClasses[$class];
342 wfDeprecated(
343 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
344 '1.23'
345 );
346 }
347
348 // For configuration backward compatibility after moving classes to namespaces (1.29)
349 $compat = [
350 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
351 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
352 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
353 ];
354
355 if ( isset( $compat[$class] ) ) {
356 $class = $compat[$class];
357 }
358
359 return $class;
360 }
361
362 /**
363 * @param LBFactory $lbFactory
364 * @param string $dbType 'mysql', 'sqlite', etc.
365 * @internal For use with service wiring
366 */
367 public static function setSchemaAliases( LBFactory $lbFactory, $dbType ) {
368 if ( $dbType === 'mysql' ) {
369 /**
370 * When SQLite indexes were introduced in r45764, it was noted that
371 * SQLite requires index names to be unique within the whole database,
372 * not just within a schema. As discussed in CR r45819, to avoid the
373 * need for a schema change on existing installations, the indexes
374 * were implicitly mapped from the new names to the old names.
375 *
376 * This mapping can be removed if DB patches are introduced to alter
377 * the relevant tables in existing installations. Note that because
378 * this index mapping applies to table creation, even new installations
379 * of MySQL have the old names (except for installations created during
380 * a period where this mapping was inappropriately removed, see
381 * T154872).
382 */
383 $lbFactory->setIndexAliases( [
384 'ar_usertext_timestamp' => 'usertext_timestamp',
385 'un_user_id' => 'user_id',
386 'un_user_ip' => 'user_ip',
387 ] );
388 }
389 }
390
391 /**
392 * Log a database deprecation warning
393 * @param string $msg Deprecation message
394 * @internal For use with service wiring
395 */
396 public static function logDeprecation( $msg ) {
397 global $wgDevelopmentWarnings;
398
399 if ( isset( self::$loggedDeprecations[$msg] ) ) {
400 return;
401 }
402 self::$loggedDeprecations[$msg] = true;
403
404 if ( $wgDevelopmentWarnings ) {
405 trigger_error( $msg, E_USER_DEPRECATED );
406 }
407 wfDebugLog( 'deprecated', $msg, 'private' );
408 }
409 }