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\Logger\LoggerFactory
;
25 use Wikimedia\Rdbms\LBFactory
;
26 use Wikimedia\Rdbms\DatabaseDomain
;
29 * MediaWiki-specific class for generating database load balancers
32 abstract class MWLBFactory
{
34 /** @var array Cache of already-logged deprecation messages */
35 private static $loggedDeprecations = [];
38 * @param array $lbConf Config for LBFactory::__construct()
39 * @param Config $mainConfig Main config object from MediaWikiServices
40 * @param ConfiguredReadOnlyMode $readOnlyMode
41 * @param BagOStuff $srvCace
42 * @param BagOStuff $mainStash
43 * @param WANObjectCache $wanCache
46 public static function applyDefaultConfig(
49 ConfiguredReadOnlyMode
$readOnlyMode,
52 WANObjectCache
$wanCache
54 global $wgCommandLineMode;
56 $typesWithSchema = self
::getDbTypesWithSchemas();
59 'localDomain' => new DatabaseDomain(
60 $mainConfig->get( 'DBname' ),
61 $mainConfig->get( 'DBmwschema' ),
62 $mainConfig->get( 'DBprefix' )
64 'profiler' => function ( $section ) {
65 return Profiler
::instance()->scopedProfileIn( $section );
67 'trxProfiler' => Profiler
::instance()->getTransactionProfiler(),
68 'replLogger' => LoggerFactory
::getInstance( 'DBReplication' ),
69 'queryLogger' => LoggerFactory
::getInstance( 'DBQuery' ),
70 'connLogger' => LoggerFactory
::getInstance( 'DBConnection' ),
71 'perfLogger' => LoggerFactory
::getInstance( 'DBPerformance' ),
72 'errorLogger' => [ MWExceptionHandler
::class, 'logException' ],
73 'deprecationLogger' => [ static::class, 'logDeprecation' ],
74 'cliMode' => $wgCommandLineMode,
75 'hostname' => wfHostname(),
76 'readOnlyReason' => $readOnlyMode->getReason(),
77 'defaultGroup' => $mainConfig->get( 'DBDefaultGroup' ),
81 // When making changes here, remember to also specify MediaWiki-specific options
82 // for Database classes in the relevant Installer subclass.
83 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
84 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple
::class ) {
85 if ( isset( $lbConf['servers'] ) ) {
86 // Server array is already explicitly configured
87 } elseif ( is_array( $mainConfig->get( 'DBservers' ) ) ) {
88 $lbConf['servers'] = [];
89 foreach ( $mainConfig->get( 'DBservers' ) as $i => $server ) {
90 $lbConf['servers'][$i] = self
::initServerInfo( $server, $mainConfig );
93 $server = self
::initServerInfo(
95 'host' => $mainConfig->get( 'DBserver' ),
96 'user' => $mainConfig->get( 'DBuser' ),
97 'password' => $mainConfig->get( 'DBpassword' ),
98 'dbname' => $mainConfig->get( 'DBname' ),
99 'type' => $mainConfig->get( 'DBtype' ),
105 $server['flags'] |
= $mainConfig->get( 'DBssl' ) ? DBO_SSL
: 0;
106 $server['flags'] |
= $mainConfig->get( 'DBcompress' ) ? DBO_COMPRESS
: 0;
108 $lbConf['servers'] = [ $server ];
110 if ( !isset( $lbConf['externalClusters'] ) ) {
111 $lbConf['externalClusters'] = $mainConfig->get( 'ExternalServers' );
114 $serversCheck = $lbConf['servers'];
115 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti
::class ) {
116 if ( isset( $lbConf['serverTemplate'] ) ) {
117 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
118 $lbConf['serverTemplate']['schema'] = $mainConfig->get( 'DBmwschema' );
120 $lbConf['serverTemplate']['sqlMode'] = $mainConfig->get( 'SQLMode' );
122 $serversCheck = [ $lbConf['serverTemplate'] ] ??
[];
125 self
::assertValidServerConfigs( $serversCheck, $mainConfig );
127 $lbConf = self
::injectObjectCaches( $lbConf, $srvCace, $mainStash, $wanCache );
135 private static function getDbTypesWithSchemas() {
136 return [ 'postgres', 'msssql' ];
140 * @param array $server
141 * @param Config $mainConfig
144 private static function initServerInfo( array $server, Config
$mainConfig ) {
145 if ( $server['type'] === 'sqlite' ) {
146 $httpMethod = $_SERVER['REQUEST_METHOD'] ??
null;
147 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
148 // See https://www.sqlite.org/lang_transaction.html
149 // See https://www.sqlite.org/lockingv3.html#shared_lock
150 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
152 'dbDirectory' => $mainConfig->get( 'SQLiteDataDir' ),
153 'trxMode' => $isHttpRead ?
'DEFERRED' : 'IMMEDIATE'
155 } elseif ( $server['type'] === 'postgres' ) {
157 'port' => $mainConfig->get( 'DBport' ),
158 // Work around the reserved word usage in MediaWiki schema
159 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
161 } elseif ( $server['type'] === 'mssql' ) {
163 'port' => $mainConfig->get( 'DBport' ),
164 'useWindowsAuth' => $mainConfig->get( 'DBWindowsAuthentication' )
168 if ( in_array( $server['type'], self
::getDbTypesWithSchemas(), true ) ) {
169 $server +
= [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
172 $flags = DBO_DEFAULT
;
173 $flags |
= $mainConfig->get( 'DebugDumpSql' ) ? DBO_DEBUG
: 0;
174 if ( $server['type'] === 'oracle' ) {
175 $flags |
= $mainConfig->get( 'DBOracleDRCP' ) ? DBO_PERSISTENT
: 0;
179 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
181 'sqlMode' => $mainConfig->get( 'SQLMode' ),
188 * @param array $lbConf
189 * @param BagOStuff $sCache
190 * @param BagOStuff $mStash
191 * @param WANObjectCache $wCache
194 private static function injectObjectCaches(
195 array $lbConf, BagOStuff
$sCache, BagOStuff
$mStash, WANObjectCache
$wCache
197 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
198 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
199 $lbConf['srvCache'] = $sCache;
201 if ( $mStash->getQoS( $mStash::ATTR_EMULATION
) > $mStash::QOS_EMULATION_SQL
) {
202 $lbConf['memStash'] = $mStash;
204 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
205 $lbConf['wanCache'] = $wCache;
212 * @param array $servers
213 * @param Config $mainConfig
215 private static function assertValidServerConfigs( array $servers, Config
$mainConfig ) {
216 $ldDB = $mainConfig->get( 'DBname' ); // local domain DB
217 $ldTP = $mainConfig->get( 'DBprefix' ); // local domain prefix
219 foreach ( $servers as $server ) {
220 $type = $server['type'] ??
null;
221 $srvDB = $server['dbname'] ??
null; // server DB
222 $srvTP = $server['tablePrefix'] ??
''; // server table prefix
224 if ( $type === 'mysql' ) {
225 // A DB name is not needed to connect to mysql; 'dbname' is useless.
226 // This field only defines the DB to use for unspecified DB domains.
227 if ( $srvDB !== null && $srvDB !== $ldDB ) {
228 self
::reportMismatchedDBs( $srvDB, $ldDB );
230 } elseif ( $type === 'postgres' ) {
231 if ( $srvTP !== '' ) {
232 self
::reportIfPrefixSet( $srvTP, $type );
236 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
237 self
::reportMismatchedPrefixes( $srvTP, $ldTP );
243 * @param string $prefix Table prefix
244 * @param string $dbType Database type
246 private static function reportIfPrefixSet( $prefix, $dbType ) {
247 $e = new UnexpectedValueException(
248 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
249 "MediaWiki does not support using a table prefix with this RDBMS type."
251 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
256 * @param string $srvDB Server config database
257 * @param string $ldDB Local DB domain database
259 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
260 $e = new UnexpectedValueException(
261 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
262 "Set \$wgDBname to the database used by this wiki project. " .
263 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
264 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
265 "use of Database::getDomainId(), and other features are not reliable when " .
266 "\$wgDBservers does not match the local wiki database/prefix."
268 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
273 * @param string $srvTP Server config table prefix
274 * @param string $ldTP Local DB domain database
276 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
277 $e = new UnexpectedValueException(
278 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
279 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
280 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
281 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
282 "use of Database::getDomainId(), and other features are not reliable when " .
283 "\$wgDBservers does not match the local wiki database/prefix."
285 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
290 * Returns the LBFactory class to use and the load balancer configuration.
292 * @todo instead of this, use a ServiceContainer for managing the different implementations.
294 * @param array $config (e.g. $wgLBFactoryConf)
295 * @return string Class name
297 public static function getLBFactoryClass( array $config ) {
298 // For configuration backward compatibility after removing
299 // underscores from class names in MediaWiki 1.23.
301 'LBFactory_Simple' => 'LBFactorySimple',
302 'LBFactory_Single' => 'LBFactorySingle',
303 'LBFactory_Multi' => 'LBFactoryMulti'
306 $class = $config['class'];
308 if ( isset( $bcClasses[$class] ) ) {
309 $class = $bcClasses[$class];
311 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
316 // For configuration backward compatibility after moving classes to namespaces (1.29)
318 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle
::class,
319 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple
::class,
320 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti
::class
323 if ( isset( $compat[$class] ) ) {
324 $class = $compat[$class];
330 public static function setSchemaAliases( LBFactory
$lbFactory, Config
$config ) {
331 if ( $config->get( 'DBtype' ) === 'mysql' ) {
333 * When SQLite indexes were introduced in r45764, it was noted that
334 * SQLite requires index names to be unique within the whole database,
335 * not just within a schema. As discussed in CR r45819, to avoid the
336 * need for a schema change on existing installations, the indexes
337 * were implicitly mapped from the new names to the old names.
339 * This mapping can be removed if DB patches are introduced to alter
340 * the relevant tables in existing installations. Note that because
341 * this index mapping applies to table creation, even new installations
342 * of MySQL have the old names (except for installations created during
343 * a period where this mapping was inappropriately removed, see
346 $lbFactory->setIndexAliases( [
347 'ar_usertext_timestamp' => 'usertext_timestamp',
348 'un_user_id' => 'user_id',
349 'un_user_ip' => 'user_ip',
355 * Log a database deprecation warning
356 * @param string $msg Deprecation message
358 public static function logDeprecation( $msg ) {
359 global $wgDevelopmentWarnings;
361 if ( isset( self
::$loggedDeprecations[$msg] ) ) {
364 self
::$loggedDeprecations[$msg] = true;
366 if ( $wgDevelopmentWarnings ) {
367 trigger_error( $msg, E_USER_DEPRECATED
);
369 wfDebugLog( 'deprecated', $msg, 'private' );