MediaWiki  1.33.0
MWLBFactory.php
Go to the documentation of this file.
1 <?php
27 
32 abstract class MWLBFactory {
33 
35  private static $loggedDeprecations = [];
36 
46  public static function applyDefaultConfig(
47  array $lbConf,
48  Config $mainConfig,
49  ConfiguredReadOnlyMode $readOnlyMode,
50  BagOStuff $srvCace,
51  BagOStuff $mainStash,
52  WANObjectCache $wanCache
53  ) {
54  global $wgCommandLineMode;
55 
56  static $typesWithSchema = [ 'postgres', 'msssql' ];
57 
58  $lbConf += [
59  'localDomain' => new DatabaseDomain(
60  $mainConfig->get( 'DBname' ),
61  $mainConfig->get( 'DBmwschema' ),
62  $mainConfig->get( 'DBprefix' )
63  ),
64  'profiler' => function ( $section ) {
65  return Profiler::instance()->scopedProfileIn( $section );
66  },
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' ),
78  ];
79 
80  $serversCheck = [];
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' ] );
90 
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' ) {
97  $server += [
98  'dbDirectory' => $mainConfig->get( 'SQLiteDataDir' ),
99  'trxMode' => $isReadRequest ? 'DEFERRED' : 'IMMEDIATE'
100  ];
101  } elseif ( $server['type'] === 'postgres' ) {
102  $server += [
103  'port' => $mainConfig->get( 'DBport' ),
104  // Work around the reserved word usage in MediaWiki schema
105  'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
106  ];
107  } elseif ( $server['type'] === 'mssql' ) {
108  $server += [
109  'port' => $mainConfig->get( 'DBport' ),
110  'useWindowsAuth' => $mainConfig->get( 'DBWindowsAuthentication' )
111  ];
112  }
113 
114  if ( in_array( $server['type'], $typesWithSchema, true ) ) {
115  $server += [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
116  }
117 
118  $server += [
119  'tablePrefix' => $mainConfig->get( 'DBprefix' ),
120  'flags' => DBO_DEFAULT,
121  'sqlMode' => $mainConfig->get( 'SQLMode' ),
122  ];
123 
124  $lbConf['servers'][$i] = $server;
125  }
126  } else {
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;
131  $server = [
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' ),
138  'load' => 1,
139  'flags' => $flags,
140  'sqlMode' => $mainConfig->get( 'SQLMode' ),
141  'trxMode' => $isReadRequest ? 'DEFERRED' : 'IMMEDIATE'
142  ];
143  if ( in_array( $server['type'], $typesWithSchema, true ) ) {
144  $server += [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
145  }
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' );
155  }
156  $lbConf['servers'] = [ $server ];
157  }
158  if ( !isset( $lbConf['externalClusters'] ) ) {
159  $lbConf['externalClusters'] = $mainConfig->get( 'ExternalServers' );
160  }
161 
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' );
167  }
168  $lbConf['serverTemplate']['sqlMode'] = $mainConfig->get( 'SQLMode' );
169  }
170  $serversCheck = $lbConf['serverTemplate'] ?? [];
171  }
172 
173  self::sanityCheckServerConfig( $serversCheck, $mainConfig );
174  $lbConf = self::applyDefaultCaching( $lbConf, $srvCace, $mainStash, $wanCache );
175 
176  return $lbConf;
177  }
178 
186  private static function applyDefaultCaching(
187  array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
188  ) {
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;
192  }
193  if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
194  $lbConf['memStash'] = $mStash;
195  }
196  if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
197  $lbConf['wanCache'] = $wCache;
198  }
199 
200  return $lbConf;
201  }
202 
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
210 
211  foreach ( $servers as $server ) {
212  $type = $server['type'] ?? null;
213  $srvDB = $server['dbname'] ?? null; // server DB
214  $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
215 
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 );
221  }
222  } elseif ( $type === 'postgres' ) {
223  if ( $srvTP !== '' ) {
224  self::reportIfPrefixSet( $srvTP, $type );
225  }
226  }
227 
228  if ( $srvTP !== '' && $srvTP !== $ldTP ) {
229  self::reportMismatchedPrefixes( $srvTP, $ldTP );
230  }
231  }
232  }
233 
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."
242  );
244  exit;
245  }
246 
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."
259  );
261  exit;
262  }
263 
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."
276  );
278  exit;
279  }
280 
289  public static function getLBFactoryClass( array $config ) {
290  // For configuration backward compatibility after removing
291  // underscores from class names in MediaWiki 1.23.
292  $bcClasses = [
293  'LBFactory_Simple' => 'LBFactorySimple',
294  'LBFactory_Single' => 'LBFactorySingle',
295  'LBFactory_Multi' => 'LBFactoryMulti'
296  ];
297 
298  $class = $config['class'];
299 
300  if ( isset( $bcClasses[$class] ) ) {
301  $class = $bcClasses[$class];
302  wfDeprecated(
303  '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
304  '1.23'
305  );
306  }
307 
308  // For configuration backward compatibility after moving classes to namespaces (1.29)
309  $compat = [
310  'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
311  'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
312  'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
313  ];
314 
315  if ( isset( $compat[$class] ) ) {
316  $class = $compat[$class];
317  }
318 
319  return $class;
320  }
321 
322  public static function setSchemaAliases( LBFactory $lbFactory, Config $config ) {
323  if ( $config->get( 'DBtype' ) === 'mysql' ) {
338  $lbFactory->setIndexAliases( [
339  'ar_usertext_timestamp' => 'usertext_timestamp',
340  'un_user_id' => 'user_id',
341  'un_user_ip' => 'user_ip',
342  ] );
343  }
344  }
345 
350  public static function logDeprecation( $msg ) {
351  global $wgDevelopmentWarnings;
352 
353  if ( isset( self::$loggedDeprecations[$msg] ) ) {
354  return;
355  }
356  self::$loggedDeprecations[$msg] = true;
357 
358  if ( $wgDevelopmentWarnings ) {
359  trigger_error( $msg, E_USER_DEPRECATED );
360  }
361  wfDebugLog( 'deprecated', $msg, 'private' );
362  }
363 }
MWLBFactory
MediaWiki-specific class for generating database load balancers.
Definition: MWLBFactory.php:32
WANObjectCache\getQoS
getQoS( $flag)
Definition: WANObjectCache.php:1966
MWLBFactory\reportMismatchedDBs
static reportMismatchedDBs( $srvDB, $ldDB)
Definition: MWLBFactory.php:251
BagOStuff\getQoS
getQoS( $flag)
Definition: BagOStuff.php:783
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:62
MWLBFactory\applyDefaultConfig
static applyDefaultConfig(array $lbConf, Config $mainConfig, ConfiguredReadOnlyMode $readOnlyMode, BagOStuff $srvCace, BagOStuff $mainStash, WANObjectCache $wanCache)
Definition: MWLBFactory.php:46
DBO_DEBUG
const DBO_DEBUG
Definition: defines.php:9
ConfiguredReadOnlyMode
A read-only mode service which does not depend on LoadBalancer.
Definition: ConfiguredReadOnlyMode.php:9
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1352
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
DBO_SSL
const DBO_SSL
Definition: defines.php:17
MWLBFactory\logDeprecation
static logDeprecation( $msg)
Log a database deprecation warning.
Definition: MWLBFactory.php:350
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1043
ConfiguredReadOnlyMode\getReason
getReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: ConfiguredReadOnlyMode.php:37
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
MWLBFactory\reportMismatchedPrefixes
static reportMismatchedPrefixes( $srvTP, $ldTP)
Definition: MWLBFactory.php:268
MWLBFactory\$loggedDeprecations
static array $loggedDeprecations
Cache of already-logged deprecation messages.
Definition: MWLBFactory.php:35
Config
Interface for configuration instances.
Definition: Config.php:28
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1078
MWLBFactory\sanityCheckServerConfig
static sanityCheckServerConfig(array $servers, Config $mainConfig)
Definition: MWLBFactory.php:207
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:27
MWLBFactory\getLBFactoryClass
static getLBFactoryClass(array $config)
Returns the LBFactory class to use and the load balancer configuration.
Definition: MWLBFactory.php:289
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
MWExceptionRenderer\AS_PRETTY
const AS_PRETTY
Definition: MWExceptionRenderer.php:31
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
DBO_COMPRESS
const DBO_COMPRESS
Definition: defines.php:18
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
MWLBFactory\setSchemaAliases
static setSchemaAliases(LBFactory $lbFactory, Config $config)
Definition: MWLBFactory.php:322
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:116
$wgDevelopmentWarnings
$wgDevelopmentWarnings
If set to true MediaWiki will throw notices for some possible error conditions and for deprecated fun...
Definition: DefaultSettings.php:6329
MWLBFactory\applyDefaultCaching
static applyDefaultCaching(array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache)
Definition: MWLBFactory.php:186
MWExceptionRenderer\output
static output( $e, $mode, $eNew=null)
Definition: MWExceptionRenderer.php:38
$section
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:3053
Wikimedia\Rdbms\LBFactory
An interface for generating database load balancers.
Definition: LBFactory.php:39
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Wikimedia
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
LoggerFactory
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
Wikimedia\Rdbms\LBFactory\setIndexAliases
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.
Definition: LBFactory.php:622
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/prefix specification for IDatabase domains.
Definition: DatabaseDomain.php:28
DBO_DEFAULT
const DBO_DEFAULT
Definition: defines.php:13
MWLBFactory\reportIfPrefixSet
static reportIfPrefixSet( $prefix, $dbType)
Definition: MWLBFactory.php:238
$type
$type
Definition: testCompression.php:48