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
74 public static function applyDefaultConfig(
76 ServiceOptions
$options,
77 ConfiguredReadOnlyMode
$readOnlyMode,
80 WANObjectCache
$wanCache
82 $options->assertRequiredOptions( self
::$applyDefaultConfigOptions );
84 global $wgCommandLineMode;
86 $typesWithSchema = self
::getDbTypesWithSchemas();
89 'localDomain' => new DatabaseDomain(
90 $options->get( 'DBname' ),
91 $options->get( 'DBmwschema' ),
92 $options->get( 'DBprefix' )
94 'profiler' => function ( $section ) {
95 return Profiler
::instance()->scopedProfileIn( $section );
97 'trxProfiler' => Profiler
::instance()->getTransactionProfiler(),
98 'replLogger' => LoggerFactory
::getInstance( 'DBReplication' ),
99 'queryLogger' => LoggerFactory
::getInstance( 'DBQuery' ),
100 'connLogger' => LoggerFactory
::getInstance( 'DBConnection' ),
101 'perfLogger' => LoggerFactory
::getInstance( 'DBPerformance' ),
102 'errorLogger' => [ MWExceptionHandler
::class, 'logException' ],
103 'deprecationLogger' => [ static::class, 'logDeprecation' ],
104 'cliMode' => $wgCommandLineMode,
105 'hostname' => wfHostname(),
106 'readOnlyReason' => $readOnlyMode->getReason(),
107 'defaultGroup' => $options->get( 'DBDefaultGroup' ),
111 // When making changes here, remember to also specify MediaWiki-specific options
112 // for Database classes in the relevant Installer subclass.
113 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
114 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple
::class ) {
115 if ( isset( $lbConf['servers'] ) ) {
116 // Server array is already explicitly configured
117 } elseif ( is_array( $options->get( 'DBservers' ) ) ) {
118 $lbConf['servers'] = [];
119 foreach ( $options->get( 'DBservers' ) as $i => $server ) {
120 $lbConf['servers'][$i] = self
::initServerInfo( $server, $options );
123 $server = self
::initServerInfo(
125 'host' => $options->get( 'DBserver' ),
126 'user' => $options->get( 'DBuser' ),
127 'password' => $options->get( 'DBpassword' ),
128 'dbname' => $options->get( 'DBname' ),
129 'type' => $options->get( 'DBtype' ),
135 $server['flags'] |
= $options->get( 'DBssl' ) ? DBO_SSL
: 0;
136 $server['flags'] |
= $options->get( 'DBcompress' ) ? DBO_COMPRESS
: 0;
138 $lbConf['servers'] = [ $server ];
140 if ( !isset( $lbConf['externalClusters'] ) ) {
141 $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
144 $serversCheck = $lbConf['servers'];
145 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti
::class ) {
146 if ( isset( $lbConf['serverTemplate'] ) ) {
147 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
148 $lbConf['serverTemplate']['schema'] = $options->get( 'DBmwschema' );
150 $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
152 $serversCheck = [ $lbConf['serverTemplate'] ] ??
[];
155 self
::assertValidServerConfigs( $serversCheck, $options->get( 'DBname' ),
156 $options->get( 'DBprefix' ) );
158 $lbConf = self
::injectObjectCaches( $lbConf, $srvCace, $mainStash, $wanCache );
166 private static function getDbTypesWithSchemas() {
167 return [ 'postgres', 'msssql' ];
171 * @param array $server
172 * @param ServiceOptions $options
175 private static function initServerInfo( array $server, ServiceOptions
$options ) {
176 if ( $server['type'] === 'sqlite' ) {
177 $httpMethod = $_SERVER['REQUEST_METHOD'] ??
null;
178 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
179 // See https://www.sqlite.org/lang_transaction.html
180 // See https://www.sqlite.org/lockingv3.html#shared_lock
181 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
183 'dbDirectory' => $options->get( 'SQLiteDataDir' ),
184 'trxMode' => $isHttpRead ?
'DEFERRED' : 'IMMEDIATE'
186 } elseif ( $server['type'] === 'postgres' ) {
188 'port' => $options->get( 'DBport' ),
189 // Work around the reserved word usage in MediaWiki schema
190 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
192 } elseif ( $server['type'] === 'oracle' ) {
194 // Work around the reserved word usage in MediaWiki schema
195 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
197 } elseif ( $server['type'] === 'mssql' ) {
199 'port' => $options->get( 'DBport' ),
200 'useWindowsAuth' => $options->get( 'DBWindowsAuthentication' )
204 if ( in_array( $server['type'], self
::getDbTypesWithSchemas(), true ) ) {
205 $server +
= [ 'schema' => $options->get( 'DBmwschema' ) ];
208 $flags = DBO_DEFAULT
;
209 $flags |
= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG
: 0;
210 $flags |
= $options->get( 'DebugLogFile' ) ? DBO_DEBUG
: 0;
211 if ( $server['type'] === 'oracle' ) {
212 $flags |
= $options->get( 'DBOracleDRCP' ) ? DBO_PERSISTENT
: 0;
216 'tablePrefix' => $options->get( 'DBprefix' ),
218 'sqlMode' => $options->get( 'SQLMode' ),
225 * @param array $lbConf
226 * @param BagOStuff $sCache
227 * @param BagOStuff $mStash
228 * @param WANObjectCache $wCache
231 private static function injectObjectCaches(
232 array $lbConf, BagOStuff
$sCache, BagOStuff
$mStash, WANObjectCache
$wCache
234 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
235 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
236 $lbConf['srvCache'] = $sCache;
238 if ( $mStash->getQoS( $mStash::ATTR_EMULATION
) > $mStash::QOS_EMULATION_SQL
) {
239 $lbConf['memStash'] = $mStash;
241 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
242 $lbConf['wanCache'] = $wCache;
249 * @param array $servers
250 * @param string $ldDB Local domain database name
251 * @param string $ldTP Local domain prefix
253 private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
254 foreach ( $servers as $server ) {
255 $type = $server['type'] ??
null;
256 $srvDB = $server['dbname'] ??
null; // server DB
257 $srvTP = $server['tablePrefix'] ??
''; // server table prefix
259 if ( $type === 'mysql' ) {
260 // A DB name is not needed to connect to mysql; 'dbname' is useless.
261 // This field only defines the DB to use for unspecified DB domains.
262 if ( $srvDB !== null && $srvDB !== $ldDB ) {
263 self
::reportMismatchedDBs( $srvDB, $ldDB );
265 } elseif ( $type === 'postgres' ) {
266 if ( $srvTP !== '' ) {
267 self
::reportIfPrefixSet( $srvTP, $type );
271 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
272 self
::reportMismatchedPrefixes( $srvTP, $ldTP );
278 * @param string $prefix Table prefix
279 * @param string $dbType Database type
281 private static function reportIfPrefixSet( $prefix, $dbType ) {
282 $e = new UnexpectedValueException(
283 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
284 "MediaWiki does not support using a table prefix with this RDBMS type."
286 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
291 * @param string $srvDB Server config database
292 * @param string $ldDB Local DB domain database
294 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
295 $e = new UnexpectedValueException(
296 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
297 "Set \$wgDBname to the database used by this wiki project. " .
298 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
299 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
300 "use of Database::getDomainId(), and other features are not reliable when " .
301 "\$wgDBservers does not match the local wiki database/prefix."
303 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
308 * @param string $srvTP Server config table prefix
309 * @param string $ldTP Local DB domain database
311 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
312 $e = new UnexpectedValueException(
313 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
314 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
315 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
316 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
317 "use of Database::getDomainId(), and other features are not reliable when " .
318 "\$wgDBservers does not match the local wiki database/prefix."
320 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
325 * Returns the LBFactory class to use and the load balancer configuration.
327 * @todo instead of this, use a ServiceContainer for managing the different implementations.
329 * @param array $config (e.g. $wgLBFactoryConf)
330 * @return string Class name
332 public static function getLBFactoryClass( array $config ) {
333 // For configuration backward compatibility after removing
334 // underscores from class names in MediaWiki 1.23.
336 'LBFactory_Simple' => 'LBFactorySimple',
337 'LBFactory_Single' => 'LBFactorySingle',
338 'LBFactory_Multi' => 'LBFactoryMulti'
341 $class = $config['class'];
343 if ( isset( $bcClasses[$class] ) ) {
344 $class = $bcClasses[$class];
346 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
351 // For configuration backward compatibility after moving classes to namespaces (1.29)
353 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle
::class,
354 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple
::class,
355 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti
::class
358 if ( isset( $compat[$class] ) ) {
359 $class = $compat[$class];
366 * @param LBFactory $lbFactory
367 * @param string $dbType 'mysql', 'sqlite', etc.
369 public static function setSchemaAliases( LBFactory
$lbFactory, $dbType ) {
370 if ( $dbType instanceof Config
) {
371 // Before 1.34 this took a whole Config just to get $dbType
372 wfDeprecated( __METHOD__
. ' with Config argument', '1.34' );
373 $dbType = $dbType->get( 'DBtype' );
375 if ( $dbType === 'mysql' ) {
377 * When SQLite indexes were introduced in r45764, it was noted that
378 * SQLite requires index names to be unique within the whole database,
379 * not just within a schema. As discussed in CR r45819, to avoid the
380 * need for a schema change on existing installations, the indexes
381 * were implicitly mapped from the new names to the old names.
383 * This mapping can be removed if DB patches are introduced to alter
384 * the relevant tables in existing installations. Note that because
385 * this index mapping applies to table creation, even new installations
386 * of MySQL have the old names (except for installations created during
387 * a period where this mapping was inappropriately removed, see
390 $lbFactory->setIndexAliases( [
391 'ar_usertext_timestamp' => 'usertext_timestamp',
392 'un_user_id' => 'user_id',
393 'un_user_ip' => 'user_ip',
399 * Log a database deprecation warning
400 * @param string $msg Deprecation message
402 public static function logDeprecation( $msg ) {
403 global $wgDevelopmentWarnings;
405 if ( isset( self
::$loggedDeprecations[$msg] ) ) {
408 self
::$loggedDeprecations[$msg] = true;
410 if ( $wgDevelopmentWarnings ) {
411 trigger_error( $msg, E_USER_DEPRECATED
);
413 wfDebugLog( 'deprecated', $msg, 'private' );