3 * Generator of database load balancing objects.
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.
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.
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
24 use MediaWiki\Config\ServiceOptions
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use Wikimedia\Rdbms\LBFactory
;
27 use Wikimedia\Rdbms\DatabaseDomain
;
30 * MediaWiki-specific class for generating database load balancers
33 abstract class MWLBFactory
{
35 /** @var array Cache of already-logged deprecation messages */
36 private static $loggedDeprecations = [];
39 * TODO Make this a const when HHVM support is dropped (T192166)
44 public static $applyDefaultConfigOptions = [
57 'DBWindowsAuthentication',
66 * @param array $lbConf Config for LBFactory::__construct()
67 * @param ServiceOptions $options
68 * @param ConfiguredReadOnlyMode $readOnlyMode
69 * @param BagOStuff $srvCace
70 * @param BagOStuff $mainStash
71 * @param WANObjectCache $wanCache
73 * @internal For use with service wiring
75 public static function applyDefaultConfig(
77 ServiceOptions
$options,
78 ConfiguredReadOnlyMode
$readOnlyMode,
81 WANObjectCache
$wanCache
83 $options->assertRequiredOptions( self
::$applyDefaultConfigOptions );
85 global $wgCommandLineMode;
87 $typesWithSchema = self
::getDbTypesWithSchemas();
90 'localDomain' => new DatabaseDomain(
91 $options->get( 'DBname' ),
92 $options->get( 'DBmwschema' ),
93 $options->get( 'DBprefix' )
95 'profiler' => function ( $section ) {
96 return Profiler
::instance()->scopedProfileIn( $section );
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' ),
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 );
124 $server = self
::initServerInfo(
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' ),
136 $server['flags'] |
= $options->get( 'DBssl' ) ? DBO_SSL
: 0;
137 $server['flags'] |
= $options->get( 'DBcompress' ) ? DBO_COMPRESS
: 0;
139 $lbConf['servers'] = [ $server ];
141 if ( !isset( $lbConf['externalClusters'] ) ) {
142 $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
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' );
151 $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
153 $serversCheck = [ $lbConf['serverTemplate'] ] ??
[];
156 self
::assertValidServerConfigs(
158 $options->get( 'DBname' ),
159 $options->get( 'DBprefix' )
162 $lbConf = self
::injectObjectCaches( $lbConf, $srvCace, $mainStash, $wanCache );
170 private static function getDbTypesWithSchemas() {
171 return [ 'postgres', 'mssql' ];
175 * @param array $server
176 * @param ServiceOptions $options
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' ] );
187 'dbDirectory' => $options->get( 'SQLiteDataDir' ),
188 'trxMode' => $isHttpRead ?
'DEFERRED' : 'IMMEDIATE'
190 } elseif ( $server['type'] === 'postgres' ) {
192 'port' => $options->get( 'DBport' ),
193 // Work around the reserved word usage in MediaWiki schema
194 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
196 } elseif ( $server['type'] === 'oracle' ) {
198 // Work around the reserved word usage in MediaWiki schema
199 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
201 } elseif ( $server['type'] === 'mssql' ) {
203 'port' => $options->get( 'DBport' ),
204 'useWindowsAuth' => $options->get( 'DBWindowsAuthentication' )
208 if ( in_array( $server['type'], self
::getDbTypesWithSchemas(), true ) ) {
209 $server +
= [ 'schema' => $options->get( 'DBmwschema' ) ];
212 $flags = DBO_DEFAULT
;
213 $flags |
= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG
: 0;
214 $flags |
= $options->get( 'DebugLogFile' ) ? DBO_DEBUG
: 0;
217 'tablePrefix' => $options->get( 'DBprefix' ),
219 'sqlMode' => $options->get( 'SQLMode' ),
226 * @param array $lbConf
227 * @param BagOStuff $sCache
228 * @param BagOStuff $mStash
229 * @param WANObjectCache $wCache
232 private static function injectObjectCaches(
233 array $lbConf, BagOStuff
$sCache, BagOStuff
$mStash, WANObjectCache
$wCache
235 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
236 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
237 $lbConf['srvCache'] = $sCache;
239 if ( $mStash->getQoS( $mStash::ATTR_EMULATION
) > $mStash::QOS_EMULATION_SQL
) {
240 $lbConf['memStash'] = $mStash;
242 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
243 $lbConf['wanCache'] = $wCache;
250 * @param array $servers
251 * @param string $ldDB Local domain database name
252 * @param string $ldTP Local domain prefix
254 private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
255 foreach ( $servers as $server ) {
256 $type = $server['type'] ??
null;
257 $srvDB = $server['dbname'] ??
null; // server DB
258 $srvTP = $server['tablePrefix'] ??
''; // server table prefix
260 if ( $type === 'mysql' ) {
261 // A DB name is not needed to connect to mysql; 'dbname' is useless.
262 // This field only defines the DB to use for unspecified DB domains.
263 if ( $srvDB !== null && $srvDB !== $ldDB ) {
264 self
::reportMismatchedDBs( $srvDB, $ldDB );
266 } elseif ( $type === 'postgres' ) {
267 if ( $srvTP !== '' ) {
268 self
::reportIfPrefixSet( $srvTP, $type );
272 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
273 self
::reportMismatchedPrefixes( $srvTP, $ldTP );
279 * @param string $prefix Table prefix
280 * @param string $dbType Database type
282 private static function reportIfPrefixSet( $prefix, $dbType ) {
283 $e = new UnexpectedValueException(
284 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
285 "MediaWiki does not support using a table prefix with this RDBMS type."
287 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
292 * @param string $srvDB Server config database
293 * @param string $ldDB Local DB domain database
295 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
296 $e = new UnexpectedValueException(
297 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
298 "Set \$wgDBname to the database used by this wiki project. " .
299 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
300 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
301 "use of Database::getDomainId(), and other features are not reliable when " .
302 "\$wgDBservers does not match the local wiki database/prefix."
304 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
309 * @param string $srvTP Server config table prefix
310 * @param string $ldTP Local DB domain database
312 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
313 $e = new UnexpectedValueException(
314 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
315 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
316 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
317 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
318 "use of Database::getDomainId(), and other features are not reliable when " .
319 "\$wgDBservers does not match the local wiki database/prefix."
321 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
326 * Returns the LBFactory class to use and the load balancer configuration.
328 * @todo instead of this, use a ServiceContainer for managing the different implementations.
330 * @param array $config (e.g. $wgLBFactoryConf)
331 * @return string Class name
332 * @internal For use with service wiring
334 public static function getLBFactoryClass( array $config ) {
335 // For configuration backward compatibility after removing
336 // underscores from class names in MediaWiki 1.23.
338 'LBFactory_Simple' => 'LBFactorySimple',
339 'LBFactory_Single' => 'LBFactorySingle',
340 'LBFactory_Multi' => 'LBFactoryMulti'
343 $class = $config['class'];
345 if ( isset( $bcClasses[$class] ) ) {
346 $class = $bcClasses[$class];
348 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
353 // For configuration backward compatibility after moving classes to namespaces (1.29)
355 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle
::class,
356 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple
::class,
357 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti
::class
360 if ( isset( $compat[$class] ) ) {
361 $class = $compat[$class];
368 * @param LBFactory $lbFactory
369 * @param string $dbType 'mysql', 'sqlite', etc.
370 * @internal For use with service wiring
372 public static function setSchemaAliases( LBFactory
$lbFactory, $dbType ) {
373 if ( $dbType === 'mysql' ) {
375 * When SQLite indexes were introduced in r45764, it was noted that
376 * SQLite requires index names to be unique within the whole database,
377 * not just within a schema. As discussed in CR r45819, to avoid the
378 * need for a schema change on existing installations, the indexes
379 * were implicitly mapped from the new names to the old names.
381 * This mapping can be removed if DB patches are introduced to alter
382 * the relevant tables in existing installations. Note that because
383 * this index mapping applies to table creation, even new installations
384 * of MySQL have the old names (except for installations created during
385 * a period where this mapping was inappropriately removed, see
388 $lbFactory->setIndexAliases( [
389 'ar_usertext_timestamp' => 'usertext_timestamp',
390 'un_user_id' => 'user_id',
391 'un_user_ip' => 'user_ip',
397 * Log a database deprecation warning
398 * @param string $msg Deprecation message
399 * @internal For use with service wiring
401 public static function logDeprecation( $msg ) {
402 global $wgDevelopmentWarnings;
404 if ( isset( self
::$loggedDeprecations[$msg] ) ) {
407 self
::$loggedDeprecations[$msg] = true;
409 if ( $wgDevelopmentWarnings ) {
410 trigger_error( $msg, E_USER_DEPRECATED
);
412 wfDebugLog( 'deprecated', $msg, 'private' );