MediaWiki  master
MWLBFactory.php
Go to the documentation of this file.
1 <?php
28 
33 abstract class MWLBFactory {
34 
36  private static $loggedDeprecations = [];
37 
44  public static $applyDefaultConfigOptions = [
45  'DBcompress',
46  'DBDefaultGroup',
47  'DBmwschema',
48  'DBname',
49  'DBpassword',
50  'DBport',
51  'DBprefix',
52  'DBserver',
53  'DBservers',
54  'DBssl',
55  'DBtype',
56  'DBuser',
57  'DBWindowsAuthentication',
58  'DebugDumpSql',
59  'DebugLogFile',
60  'ExternalServers',
61  'SQLiteDataDir',
62  'SQLMode',
63  ];
64 
74  public static function applyDefaultConfig(
75  array $lbConf,
77  ConfiguredReadOnlyMode $readOnlyMode,
78  BagOStuff $srvCace,
79  BagOStuff $mainStash,
80  WANObjectCache $wanCache
81  ) {
82  $options->assertRequiredOptions( self::$applyDefaultConfigOptions );
83 
84  global $wgCommandLineMode;
85 
86  $typesWithSchema = self::getDbTypesWithSchemas();
87 
88  $lbConf += [
89  'localDomain' => new DatabaseDomain(
90  $options->get( 'DBname' ),
91  $options->get( 'DBmwschema' ),
92  $options->get( 'DBprefix' )
93  ),
94  'profiler' => function ( $section ) {
95  return Profiler::instance()->scopedProfileIn( $section );
96  },
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' ),
108  ];
109 
110  $serversCheck = [];
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 );
121  }
122  } else {
123  $server = self::initServerInfo(
124  [
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' ),
130  'load' => 1
131  ],
132  $options
133  );
134 
135  $server['flags'] |= $options->get( 'DBssl' ) ? DBO_SSL : 0;
136  $server['flags'] |= $options->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
137 
138  $lbConf['servers'] = [ $server ];
139  }
140  if ( !isset( $lbConf['externalClusters'] ) ) {
141  $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
142  }
143 
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' );
149  }
150  $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
151  }
152  $serversCheck = [ $lbConf['serverTemplate'] ] ?? [];
153  }
154 
155  self::assertValidServerConfigs( $serversCheck, $options->get( 'DBname' ),
156  $options->get( 'DBprefix' ) );
157 
158  $lbConf = self::injectObjectCaches( $lbConf, $srvCace, $mainStash, $wanCache );
159 
160  return $lbConf;
161  }
162 
166  private static function getDbTypesWithSchemas() {
167  return [ 'postgres', 'msssql' ];
168  }
169 
175  private static function initServerInfo( array $server, ServiceOptions $options ) {
176  if ( $server['type'] === 'sqlite' ) {
177  $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
178  // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
179  // See https://www.sqlite.org/lang_transaction.html
180  // See https://www.sqlite.org/lockingv3.html#shared_lock
181  $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
182  $server += [
183  'dbDirectory' => $options->get( 'SQLiteDataDir' ),
184  'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
185  ];
186  } elseif ( $server['type'] === 'postgres' ) {
187  $server += [
188  'port' => $options->get( 'DBport' ),
189  // Work around the reserved word usage in MediaWiki schema
190  'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
191  ];
192  } elseif ( $server['type'] === 'oracle' ) {
193  $server += [
194  // Work around the reserved word usage in MediaWiki schema
195  'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
196  ];
197  } elseif ( $server['type'] === 'mssql' ) {
198  $server += [
199  'port' => $options->get( 'DBport' ),
200  'useWindowsAuth' => $options->get( 'DBWindowsAuthentication' )
201  ];
202  }
203 
204  if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
205  $server += [ 'schema' => $options->get( 'DBmwschema' ) ];
206  }
207 
208  $flags = DBO_DEFAULT;
209  $flags |= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG : 0;
210  $flags |= $options->get( 'DebugLogFile' ) ? DBO_DEBUG : 0;
211  if ( $server['type'] === 'oracle' ) {
212  $flags |= $options->get( 'DBOracleDRCP' ) ? DBO_PERSISTENT : 0;
213  }
214 
215  $server += [
216  'tablePrefix' => $options->get( 'DBprefix' ),
217  'flags' => $flags,
218  'sqlMode' => $options->get( 'SQLMode' ),
219  ];
220 
221  return $server;
222  }
223 
231  private static function injectObjectCaches(
232  array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
233  ) {
234  // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
235  if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
236  $lbConf['srvCache'] = $sCache;
237  }
238  if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
239  $lbConf['memStash'] = $mStash;
240  }
241  if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
242  $lbConf['wanCache'] = $wCache;
243  }
244 
245  return $lbConf;
246  }
247 
253  private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
254  foreach ( $servers as $server ) {
255  $type = $server['type'] ?? null;
256  $srvDB = $server['dbname'] ?? null; // server DB
257  $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
258 
259  if ( $type === 'mysql' ) {
260  // A DB name is not needed to connect to mysql; 'dbname' is useless.
261  // This field only defines the DB to use for unspecified DB domains.
262  if ( $srvDB !== null && $srvDB !== $ldDB ) {
263  self::reportMismatchedDBs( $srvDB, $ldDB );
264  }
265  } elseif ( $type === 'postgres' ) {
266  if ( $srvTP !== '' ) {
267  self::reportIfPrefixSet( $srvTP, $type );
268  }
269  }
270 
271  if ( $srvTP !== '' && $srvTP !== $ldTP ) {
272  self::reportMismatchedPrefixes( $srvTP, $ldTP );
273  }
274  }
275  }
276 
281  private static function reportIfPrefixSet( $prefix, $dbType ) {
283  "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
284  "MediaWiki does not support using a table prefix with this RDBMS type."
285  );
287  exit;
288  }
289 
294  private static function reportMismatchedDBs( $srvDB, $ldDB ) {
296  "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
297  "Set \$wgDBname to the database used by this wiki project. " .
298  "There is rarely a need to set 'dbname' in \$wgDBservers. " .
299  "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
300  "use of Database::getDomainId(), and other features are not reliable when " .
301  "\$wgDBservers does not match the local wiki database/prefix."
302  );
304  exit;
305  }
306 
311  private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
313  "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
314  "Set \$wgDBprefix to the table prefix used by this wiki project. " .
315  "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
316  "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
317  "use of Database::getDomainId(), and other features are not reliable when " .
318  "\$wgDBservers does not match the local wiki database/prefix."
319  );
321  exit;
322  }
323 
332  public static function getLBFactoryClass( array $config ) {
333  // For configuration backward compatibility after removing
334  // underscores from class names in MediaWiki 1.23.
335  $bcClasses = [
336  'LBFactory_Simple' => 'LBFactorySimple',
337  'LBFactory_Single' => 'LBFactorySingle',
338  'LBFactory_Multi' => 'LBFactoryMulti'
339  ];
340 
341  $class = $config['class'];
342 
343  if ( isset( $bcClasses[$class] ) ) {
344  $class = $bcClasses[$class];
345  wfDeprecated(
346  '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
347  '1.23'
348  );
349  }
350 
351  // For configuration backward compatibility after moving classes to namespaces (1.29)
352  $compat = [
353  'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
354  'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
355  'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
356  ];
357 
358  if ( isset( $compat[$class] ) ) {
359  $class = $compat[$class];
360  }
361 
362  return $class;
363  }
364 
369  public static function setSchemaAliases( LBFactory $lbFactory, $dbType ) {
370  if ( $dbType instanceof Config ) {
371  // Before 1.34 this took a whole Config just to get $dbType
372  wfDeprecated( __METHOD__ . ' with Config argument', '1.34' );
373  $dbType = $dbType->get( 'DBtype' );
374  }
375  if ( $dbType === 'mysql' ) {
390  $lbFactory->setIndexAliases( [
391  'ar_usertext_timestamp' => 'usertext_timestamp',
392  'un_user_id' => 'user_id',
393  'un_user_ip' => 'user_ip',
394  ] );
395  }
396  }
397 
402  public static function logDeprecation( $msg ) {
403  global $wgDevelopmentWarnings;
404 
405  if ( isset( self::$loggedDeprecations[$msg] ) ) {
406  return;
407  }
408  self::$loggedDeprecations[$msg] = true;
409 
410  if ( $wgDevelopmentWarnings ) {
411  trigger_error( $msg, E_USER_DEPRECATED );
412  }
413  wfDebugLog( 'deprecated', $msg, 'private' );
414  }
415 }
An interface for generating database load balancers.
Definition: LBFactory.php:40
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
static instance()
Singleton.
Definition: Profiler.php:62
wfHostname()
Fetch server name for use in error reporting etc.
static getDbTypesWithSchemas()
static setSchemaAliases(LBFactory $lbFactory, $dbType)
A read-only mode service which does not depend on LoadBalancer.
const DBO_PERSISTENT
Definition: defines.php:14
A class for passing options to services.
static initServerInfo(array $server, ServiceOptions $options)
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
static assertValidServerConfigs(array $servers, $ldDB, $ldTP)
Interface for configuration instances.
Definition: Config.php:28
const DBO_DEBUG
Definition: defines.php:9
static logDeprecation( $msg)
Log a database deprecation warning.
static reportMismatchedPrefixes( $srvTP, $ldTP)
static array $loggedDeprecations
Cache of already-logged deprecation messages.
Definition: MWLBFactory.php:36
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
static injectObjectCaches(array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
static applyDefaultConfig(array $lbConf, ServiceOptions $options, ConfiguredReadOnlyMode $readOnlyMode, BagOStuff $srvCace, BagOStuff $mainStash, WANObjectCache $wanCache)
Definition: MWLBFactory.php:74
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
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:3051
getQoS( $flag)
Definition: BagOStuff.php:986
static output( $e, $mode, $eNew=null)
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.
Definition: LBFactory.php:633
getReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys, without regard for order.
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
const DBO_DEFAULT
Definition: defines.php:13
Class to handle database/prefix specification for IDatabase domains.
static reportIfPrefixSet( $prefix, $dbType)
static array $applyDefaultConfigOptions
TODO Make this a const when HHVM support is dropped (T192166)
Definition: MWLBFactory.php:44
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
static getLBFactoryClass(array $config)
Returns the LBFactory class to use and the load balancer configuration.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
global $wgCommandLineMode
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
MediaWiki-specific class for generating database load balancers.
Definition: MWLBFactory.php:33
const DBO_SSL
Definition: defines.php:17
static reportMismatchedDBs( $srvDB, $ldDB)
$wgDevelopmentWarnings
If set to true MediaWiki will throw notices for some possible error conditions and for deprecated fun...
const DBO_COMPRESS
Definition: defines.php:18