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 static $typesWithSchema = [ 'postgres', 'msssql' ];
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 $httpMethod = $_SERVER['REQUEST_METHOD'] ??
null;
86 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
87 // See https://www.sqlite.org/lang_transaction.html
88 // See https://www.sqlite.org/lockingv3.html#shared_lock
89 $isReadRequest = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
91 if ( isset( $lbConf['servers'] ) ) {
92 // Server array is already explicitly configured; leave alone
93 } elseif ( is_array( $mainConfig->get( 'DBservers' ) ) ) {
94 $lbConf['servers'] = [];
95 foreach ( $mainConfig->get( 'DBservers' ) as $i => $server ) {
96 if ( $server['type'] === 'sqlite' ) {
98 'dbDirectory' => $mainConfig->get( 'SQLiteDataDir' ),
99 'trxMode' => $isReadRequest ?
'DEFERRED' : 'IMMEDIATE'
101 } elseif ( $server['type'] === 'postgres' ) {
103 'port' => $mainConfig->get( 'DBport' ),
104 // Work around the reserved word usage in MediaWiki schema
105 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
107 } elseif ( $server['type'] === 'mssql' ) {
109 'port' => $mainConfig->get( 'DBport' ),
110 'useWindowsAuth' => $mainConfig->get( 'DBWindowsAuthentication' )
114 if ( in_array( $server['type'], $typesWithSchema, true ) ) {
115 $server +
= [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
119 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
120 'flags' => DBO_DEFAULT
,
121 'sqlMode' => $mainConfig->get( 'SQLMode' ),
124 $lbConf['servers'][$i] = $server;
127 $flags = DBO_DEFAULT
;
128 $flags |
= $mainConfig->get( 'DebugDumpSql' ) ? DBO_DEBUG
: 0;
129 $flags |
= $mainConfig->get( 'DBssl' ) ? DBO_SSL
: 0;
130 $flags |
= $mainConfig->get( 'DBcompress' ) ? DBO_COMPRESS
: 0;
132 'host' => $mainConfig->get( 'DBserver' ),
133 'user' => $mainConfig->get( 'DBuser' ),
134 'password' => $mainConfig->get( 'DBpassword' ),
135 'dbname' => $mainConfig->get( 'DBname' ),
136 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
137 'type' => $mainConfig->get( 'DBtype' ),
140 'sqlMode' => $mainConfig->get( 'SQLMode' ),
141 'trxMode' => $isReadRequest ?
'DEFERRED' : 'IMMEDIATE'
143 if ( in_array( $server['type'], $typesWithSchema, true ) ) {
144 $server +
= [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
146 if ( $server['type'] === 'sqlite' ) {
147 $server[ 'dbDirectory'] = $mainConfig->get( 'SQLiteDataDir' );
148 } elseif ( $server['type'] === 'postgres' ) {
149 $server['port'] = $mainConfig->get( 'DBport' );
150 // Work around the reserved word usage in MediaWiki schema
151 $server['keywordTableMap'] = [ 'user' => 'mwuser', 'text' => 'pagecontent' ];
152 } elseif ( $server['type'] === 'mssql' ) {
153 $server['port'] = $mainConfig->get( 'DBport' );
154 $server['useWindowsAuth'] = $mainConfig->get( 'DBWindowsAuthentication' );
156 $lbConf['servers'] = [ $server ];
158 if ( !isset( $lbConf['externalClusters'] ) ) {
159 $lbConf['externalClusters'] = $mainConfig->get( 'ExternalServers' );
162 $serversCheck = $lbConf['servers'];
163 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti
::class ) {
164 if ( isset( $lbConf['serverTemplate'] ) ) {
165 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
166 $lbConf['serverTemplate']['schema'] = $mainConfig->get( 'DBmwschema' );
168 $lbConf['serverTemplate']['sqlMode'] = $mainConfig->get( 'SQLMode' );
170 $serversCheck = $lbConf['serverTemplate'] ??
[];
173 self
::sanityCheckServerConfig( $serversCheck, $mainConfig );
174 $lbConf = self
::applyDefaultCaching( $lbConf, $srvCace, $mainStash, $wanCache );
180 * @param array $lbConf
181 * @param BagOStuff $sCache
182 * @param BagOStuff $mStash
183 * @param WANObjectCache $wCache
186 private static function applyDefaultCaching(
187 array $lbConf, BagOStuff
$sCache, BagOStuff
$mStash, WANObjectCache
$wCache
189 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
190 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
191 $lbConf['srvCache'] = $sCache;
193 if ( $mStash->getQoS( $mStash::ATTR_EMULATION
) > $mStash::QOS_EMULATION_SQL
) {
194 $lbConf['memStash'] = $mStash;
196 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
197 $lbConf['wanCache'] = $wCache;
204 * @param array $servers
205 * @param Config $mainConfig
207 private static function sanityCheckServerConfig( array $servers, Config
$mainConfig ) {
208 $ldDB = $mainConfig->get( 'DBname' ); // local domain DB
209 $ldTP = $mainConfig->get( 'DBprefix' ); // local domain prefix
211 foreach ( $servers as $server ) {
212 $type = $server['type'] ??
null;
213 $srvDB = $server['dbname'] ??
null; // server DB
214 $srvTP = $server['tablePrefix'] ??
''; // server table prefix
216 if ( $type === 'mysql' ) {
217 // A DB name is not needed to connect to mysql; 'dbname' is useless.
218 // This field only defines the DB to use for unspecified DB domains.
219 if ( $srvDB !== null && $srvDB !== $ldDB ) {
220 self
::reportMismatchedDBs( $srvDB, $ldDB );
222 } elseif ( $type === 'postgres' ) {
223 if ( $srvTP !== '' ) {
224 self
::reportIfPrefixSet( $srvTP, $type );
228 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
229 self
::reportMismatchedPrefixes( $srvTP, $ldTP );
235 * @param string $prefix Table prefix
236 * @param string $dbType Database type
238 private static function reportIfPrefixSet( $prefix, $dbType ) {
239 $e = new UnexpectedValueException(
240 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
241 "MediaWiki does not support using a table prefix with this RDBMS type."
243 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
248 * @param string $srvDB Server config database
249 * @param string $ldDB Local DB domain database
251 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
252 $e = new UnexpectedValueException(
253 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
254 "Set \$wgDBname to the database used by this wiki project. " .
255 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
256 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
257 "use of Database::getDomainId(), and other features are not reliable when " .
258 "\$wgDBservers does not match the local wiki database/prefix."
260 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
265 * @param string $srvTP Server config table prefix
266 * @param string $ldTP Local DB domain database
268 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
269 $e = new UnexpectedValueException(
270 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
271 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
272 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
273 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
274 "use of Database::getDomainId(), and other features are not reliable when " .
275 "\$wgDBservers does not match the local wiki database/prefix."
277 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
282 * Returns the LBFactory class to use and the load balancer configuration.
284 * @todo instead of this, use a ServiceContainer for managing the different implementations.
286 * @param array $config (e.g. $wgLBFactoryConf)
287 * @return string Class name
289 public static function getLBFactoryClass( array $config ) {
290 // For configuration backward compatibility after removing
291 // underscores from class names in MediaWiki 1.23.
293 'LBFactory_Simple' => 'LBFactorySimple',
294 'LBFactory_Single' => 'LBFactorySingle',
295 'LBFactory_Multi' => 'LBFactoryMulti'
298 $class = $config['class'];
300 if ( isset( $bcClasses[$class] ) ) {
301 $class = $bcClasses[$class];
303 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
308 // For configuration backward compatibility after moving classes to namespaces (1.29)
310 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle
::class,
311 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple
::class,
312 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti
::class
315 if ( isset( $compat[$class] ) ) {
316 $class = $compat[$class];
322 public static function setSchemaAliases( LBFactory
$lbFactory, Config
$config ) {
323 if ( $config->get( 'DBtype' ) === 'mysql' ) {
325 * When SQLite indexes were introduced in r45764, it was noted that
326 * SQLite requires index names to be unique within the whole database,
327 * not just within a schema. As discussed in CR r45819, to avoid the
328 * need for a schema change on existing installations, the indexes
329 * were implicitly mapped from the new names to the old names.
331 * This mapping can be removed if DB patches are introduced to alter
332 * the relevant tables in existing installations. Note that because
333 * this index mapping applies to table creation, even new installations
334 * of MySQL have the old names (except for installations created during
335 * a period where this mapping was inappropriately removed, see
338 $lbFactory->setIndexAliases( [
339 'ar_usertext_timestamp' => 'usertext_timestamp',
340 'un_user_id' => 'user_id',
341 'un_user_ip' => 'user_ip',
347 * Log a database deprecation warning
348 * @param string $msg Deprecation message
350 public static function logDeprecation( $msg ) {
351 global $wgDevelopmentWarnings;
353 if ( isset( self
::$loggedDeprecations[$msg] ) ) {
356 self
::$loggedDeprecations[$msg] = true;
358 if ( $wgDevelopmentWarnings ) {
359 trigger_error( $msg, E_USER_DEPRECATED
);
361 wfDebugLog( 'deprecated', $msg, 'private' );