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\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 * TODO Make this a const when HHVM support is dropped (T192166)
43 public static $applyDefaultConfigOptions = [
56 'DBWindowsAuthentication',
65 * @param array $lbConf Config for LBFactory::__construct()
66 * @param ServiceOptions $options
67 * @param ConfiguredReadOnlyMode $readOnlyMode
68 * @param BagOStuff $srvCache
69 * @param BagOStuff $mainStash
70 * @param WANObjectCache $wanCache
72 * @internal For use with service wiring
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(
157 $options->get( 'DBname' ),
158 $options->get( 'DBprefix' )
161 $lbConf = self
::injectObjectCaches( $lbConf, $srvCache, $mainStash, $wanCache );
169 private static function getDbTypesWithSchemas() {
170 return [ 'postgres' ];
174 * @param array $server
175 * @param ServiceOptions $options
178 private static function initServerInfo( array $server, ServiceOptions
$options ) {
179 if ( $server['type'] === 'sqlite' ) {
180 $httpMethod = $_SERVER['REQUEST_METHOD'] ??
null;
181 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
182 // See https://www.sqlite.org/lang_transaction.html
183 // See https://www.sqlite.org/lockingv3.html#shared_lock
184 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
186 'dbDirectory' => $options->get( 'SQLiteDataDir' ),
187 'trxMode' => $isHttpRead ?
'DEFERRED' : 'IMMEDIATE'
189 } elseif ( $server['type'] === 'postgres' ) {
191 'port' => $options->get( 'DBport' ),
192 // Work around the reserved word usage in MediaWiki schema
193 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
197 if ( in_array( $server['type'], self
::getDbTypesWithSchemas(), true ) ) {
198 $server +
= [ 'schema' => $options->get( 'DBmwschema' ) ];
201 $flags = DBO_DEFAULT
;
202 $flags |
= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG
: 0;
203 $flags |
= $options->get( 'DebugLogFile' ) ? DBO_DEBUG
: 0;
206 'tablePrefix' => $options->get( 'DBprefix' ),
208 'sqlMode' => $options->get( 'SQLMode' ),
215 * @param array $lbConf
216 * @param BagOStuff $sCache
217 * @param BagOStuff $mStash
218 * @param WANObjectCache $wCache
221 private static function injectObjectCaches(
222 array $lbConf, BagOStuff
$sCache, BagOStuff
$mStash, WANObjectCache
$wCache
224 // Fallback if APC style caching is not an option
225 if ( $sCache instanceof EmptyBagOStuff
) {
226 $sCache = new HashBagOStuff( [ 'maxKeys' => 100 ] );
229 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
230 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
231 $lbConf['srvCache'] = $sCache;
233 if ( $mStash->getQoS( $mStash::ATTR_EMULATION
) > $mStash::QOS_EMULATION_SQL
) {
234 $lbConf['memStash'] = $mStash;
236 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
237 $lbConf['wanCache'] = $wCache;
244 * @param array $servers
245 * @param string $ldDB Local domain database name
246 * @param string $ldTP Local domain prefix
248 private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
249 foreach ( $servers as $server ) {
250 $type = $server['type'] ??
null;
251 $srvDB = $server['dbname'] ??
null; // server DB
252 $srvTP = $server['tablePrefix'] ??
''; // server table prefix
254 if ( $type === 'mysql' ) {
255 // A DB name is not needed to connect to mysql; 'dbname' is useless.
256 // This field only defines the DB to use for unspecified DB domains.
257 if ( $srvDB !== null && $srvDB !== $ldDB ) {
258 self
::reportMismatchedDBs( $srvDB, $ldDB );
260 } elseif ( $type === 'postgres' ) {
261 if ( $srvTP !== '' ) {
262 self
::reportIfPrefixSet( $srvTP, $type );
266 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
267 self
::reportMismatchedPrefixes( $srvTP, $ldTP );
273 * @param string $prefix Table prefix
274 * @param string $dbType Database type
276 private static function reportIfPrefixSet( $prefix, $dbType ) {
277 $e = new UnexpectedValueException(
278 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
279 "MediaWiki does not support using a table prefix with this RDBMS type."
281 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
286 * @param string $srvDB Server config database
287 * @param string $ldDB Local DB domain database
289 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
290 $e = new UnexpectedValueException(
291 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
292 "Set \$wgDBname to the database used by this wiki project. " .
293 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
294 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
295 "use of Database::getDomainId(), and other features are not reliable when " .
296 "\$wgDBservers does not match the local wiki database/prefix."
298 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
303 * @param string $srvTP Server config table prefix
304 * @param string $ldTP Local DB domain database
306 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
307 $e = new UnexpectedValueException(
308 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
309 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
310 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
311 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
312 "use of Database::getDomainId(), and other features are not reliable when " .
313 "\$wgDBservers does not match the local wiki database/prefix."
315 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
320 * Returns the LBFactory class to use and the load balancer configuration.
322 * @todo instead of this, use a ServiceContainer for managing the different implementations.
324 * @param array $config (e.g. $wgLBFactoryConf)
325 * @return string Class name
326 * @internal For use with service wiring
328 public static function getLBFactoryClass( array $config ) {
329 // For configuration backward compatibility after removing
330 // underscores from class names in MediaWiki 1.23.
332 'LBFactory_Simple' => 'LBFactorySimple',
333 'LBFactory_Single' => 'LBFactorySingle',
334 'LBFactory_Multi' => 'LBFactoryMulti'
337 $class = $config['class'];
339 if ( isset( $bcClasses[$class] ) ) {
340 $class = $bcClasses[$class];
342 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
347 // For configuration backward compatibility after moving classes to namespaces (1.29)
349 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle
::class,
350 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple
::class,
351 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti
::class
354 if ( isset( $compat[$class] ) ) {
355 $class = $compat[$class];
362 * Log a database deprecation warning
363 * @param string $msg Deprecation message
364 * @internal For use with service wiring
366 public static function logDeprecation( $msg ) {
367 global $wgDevelopmentWarnings;
369 if ( isset( self
::$loggedDeprecations[$msg] ) ) {
372 self
::$loggedDeprecations[$msg] = true;
374 if ( $wgDevelopmentWarnings ) {
375 trigger_error( $msg, E_USER_DEPRECATED
);
377 wfDebugLog( 'deprecated', $msg, 'private' );