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 = [];
41 public const APPLY_DEFAULT_CONFIG_OPTIONS
= [
54 'DBWindowsAuthentication',
63 * @param array $lbConf Config for LBFactory::__construct()
64 * @param ServiceOptions $options
65 * @param ConfiguredReadOnlyMode $readOnlyMode
66 * @param BagOStuff $srvCache
67 * @param BagOStuff $mainStash
68 * @param WANObjectCache $wanCache
70 * @internal For use with service wiring
72 public static function applyDefaultConfig(
74 ServiceOptions
$options,
75 ConfiguredReadOnlyMode
$readOnlyMode,
78 WANObjectCache
$wanCache
80 $options->assertRequiredOptions( self
::APPLY_DEFAULT_CONFIG_OPTIONS
);
82 global $wgCommandLineMode;
84 $typesWithSchema = self
::getDbTypesWithSchemas();
87 'localDomain' => new DatabaseDomain(
88 $options->get( 'DBname' ),
89 $options->get( 'DBmwschema' ),
90 $options->get( 'DBprefix' )
92 'profiler' => function ( $section ) {
93 return Profiler
::instance()->scopedProfileIn( $section );
95 'trxProfiler' => Profiler
::instance()->getTransactionProfiler(),
96 'replLogger' => LoggerFactory
::getInstance( 'DBReplication' ),
97 'queryLogger' => LoggerFactory
::getInstance( 'DBQuery' ),
98 'connLogger' => LoggerFactory
::getInstance( 'DBConnection' ),
99 'perfLogger' => LoggerFactory
::getInstance( 'DBPerformance' ),
100 'errorLogger' => [ MWExceptionHandler
::class, 'logException' ],
101 'deprecationLogger' => [ static::class, 'logDeprecation' ],
102 'cliMode' => $wgCommandLineMode,
103 'hostname' => wfHostname(),
104 'readOnlyReason' => $readOnlyMode->getReason(),
105 'defaultGroup' => $options->get( 'DBDefaultGroup' ),
109 // When making changes here, remember to also specify MediaWiki-specific options
110 // for Database classes in the relevant Installer subclass.
111 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
112 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple
::class ) {
113 if ( isset( $lbConf['servers'] ) ) {
114 // Server array is already explicitly configured
115 } elseif ( is_array( $options->get( 'DBservers' ) ) ) {
116 $lbConf['servers'] = [];
117 foreach ( $options->get( 'DBservers' ) as $i => $server ) {
118 $lbConf['servers'][$i] = self
::initServerInfo( $server, $options );
121 $server = self
::initServerInfo(
123 'host' => $options->get( 'DBserver' ),
124 'user' => $options->get( 'DBuser' ),
125 'password' => $options->get( 'DBpassword' ),
126 'dbname' => $options->get( 'DBname' ),
127 'type' => $options->get( 'DBtype' ),
133 $server['flags'] |
= $options->get( 'DBssl' ) ? DBO_SSL
: 0;
134 $server['flags'] |
= $options->get( 'DBcompress' ) ? DBO_COMPRESS
: 0;
136 $lbConf['servers'] = [ $server ];
138 if ( !isset( $lbConf['externalClusters'] ) ) {
139 $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
142 $serversCheck = $lbConf['servers'];
143 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti
::class ) {
144 if ( isset( $lbConf['serverTemplate'] ) ) {
145 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
146 $lbConf['serverTemplate']['schema'] = $options->get( 'DBmwschema' );
148 $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
150 $serversCheck = [ $lbConf['serverTemplate'] ] ??
[];
153 self
::assertValidServerConfigs(
155 $options->get( 'DBname' ),
156 $options->get( 'DBprefix' )
159 $lbConf = self
::injectObjectCaches( $lbConf, $srvCache, $mainStash, $wanCache );
167 private static function getDbTypesWithSchemas() {
168 return [ 'postgres' ];
172 * @param array $server
173 * @param ServiceOptions $options
176 private static function initServerInfo( array $server, ServiceOptions
$options ) {
177 if ( $server['type'] === 'sqlite' ) {
178 $httpMethod = $_SERVER['REQUEST_METHOD'] ??
null;
179 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
180 // See https://www.sqlite.org/lang_transaction.html
181 // See https://www.sqlite.org/lockingv3.html#shared_lock
182 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
184 'dbDirectory' => $options->get( 'SQLiteDataDir' ),
185 'trxMode' => $isHttpRead ?
'DEFERRED' : 'IMMEDIATE'
187 } elseif ( $server['type'] === 'postgres' ) {
189 'port' => $options->get( 'DBport' ),
190 // Work around the reserved word usage in MediaWiki schema
191 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
195 if ( in_array( $server['type'], self
::getDbTypesWithSchemas(), true ) ) {
196 $server +
= [ 'schema' => $options->get( 'DBmwschema' ) ];
199 $flags = DBO_DEFAULT
;
200 $flags |
= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG
: 0;
201 $flags |
= $options->get( 'DebugLogFile' ) ? DBO_DEBUG
: 0;
204 'tablePrefix' => $options->get( 'DBprefix' ),
206 'sqlMode' => $options->get( 'SQLMode' ),
213 * @param array $lbConf
214 * @param BagOStuff $sCache
215 * @param BagOStuff $mStash
216 * @param WANObjectCache $wCache
219 private static function injectObjectCaches(
220 array $lbConf, BagOStuff
$sCache, BagOStuff
$mStash, WANObjectCache
$wCache
222 // Fallback if APC style caching is not an option
223 if ( $sCache instanceof EmptyBagOStuff
) {
224 $sCache = new HashBagOStuff( [ 'maxKeys' => 100 ] );
227 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
228 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
229 $lbConf['srvCache'] = $sCache;
231 if ( $mStash->getQoS( $mStash::ATTR_EMULATION
) > $mStash::QOS_EMULATION_SQL
) {
232 $lbConf['memStash'] = $mStash;
234 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
235 $lbConf['wanCache'] = $wCache;
242 * @param array $servers
243 * @param string $ldDB Local domain database name
244 * @param string $ldTP Local domain prefix
246 private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
247 foreach ( $servers as $server ) {
248 $type = $server['type'] ??
null;
249 $srvDB = $server['dbname'] ??
null; // server DB
250 $srvTP = $server['tablePrefix'] ??
''; // server table prefix
252 if ( $type === 'mysql' ) {
253 // A DB name is not needed to connect to mysql; 'dbname' is useless.
254 // This field only defines the DB to use for unspecified DB domains.
255 if ( $srvDB !== null && $srvDB !== $ldDB ) {
256 self
::reportMismatchedDBs( $srvDB, $ldDB );
258 } elseif ( $type === 'postgres' ) {
259 if ( $srvTP !== '' ) {
260 self
::reportIfPrefixSet( $srvTP, $type );
264 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
265 self
::reportMismatchedPrefixes( $srvTP, $ldTP );
271 * @param string $prefix Table prefix
272 * @param string $dbType Database type
274 private static function reportIfPrefixSet( $prefix, $dbType ) {
275 $e = new UnexpectedValueException(
276 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
277 "MediaWiki does not support using a table prefix with this RDBMS type."
279 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
284 * @param string $srvDB Server config database
285 * @param string $ldDB Local DB domain database
287 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
288 $e = new UnexpectedValueException(
289 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
290 "Set \$wgDBname to the database used by this wiki project. " .
291 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
292 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
293 "use of Database::getDomainId(), and other features are not reliable when " .
294 "\$wgDBservers does not match the local wiki database/prefix."
296 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
301 * @param string $srvTP Server config table prefix
302 * @param string $ldTP Local DB domain database
304 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
305 $e = new UnexpectedValueException(
306 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
307 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
308 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
309 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
310 "use of Database::getDomainId(), and other features are not reliable when " .
311 "\$wgDBservers does not match the local wiki database/prefix."
313 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
318 * Returns the LBFactory class to use and the load balancer configuration.
320 * @todo instead of this, use a ServiceContainer for managing the different implementations.
322 * @param array $config (e.g. $wgLBFactoryConf)
323 * @return string Class name
324 * @internal For use with service wiring
326 public static function getLBFactoryClass( array $config ) {
327 // For configuration backward compatibility after removing
328 // underscores from class names in MediaWiki 1.23.
330 'LBFactory_Simple' => 'LBFactorySimple',
331 'LBFactory_Single' => 'LBFactorySingle',
332 'LBFactory_Multi' => 'LBFactoryMulti'
335 $class = $config['class'];
337 if ( isset( $bcClasses[$class] ) ) {
338 $class = $bcClasses[$class];
340 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
345 // For configuration backward compatibility after moving classes to namespaces (1.29)
347 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle
::class,
348 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple
::class,
349 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti
::class
352 if ( isset( $compat[$class] ) ) {
353 $class = $compat[$class];
360 * Log a database deprecation warning
361 * @param string $msg Deprecation message
362 * @internal For use with service wiring
364 public static function logDeprecation( $msg ) {
365 global $wgDevelopmentWarnings;
367 if ( isset( self
::$loggedDeprecations[$msg] ) ) {
370 self
::$loggedDeprecations[$msg] = true;
372 if ( $wgDevelopmentWarnings ) {
373 trigger_error( $msg, E_USER_DEPRECATED
);
375 wfDebugLog( 'deprecated', $msg, 'private' );