MediaWiki  master
MWLBFactory.php
Go to the documentation of this file.
1 <?php
27 
32 abstract class MWLBFactory {
33 
35  private static $loggedDeprecations = [];
36 
41  public const APPLY_DEFAULT_CONFIG_OPTIONS = [
42  'DBcompress',
43  'DBDefaultGroup',
44  'DBmwschema',
45  'DBname',
46  'DBpassword',
47  'DBport',
48  'DBprefix',
49  'DBserver',
50  'DBservers',
51  'DBssl',
52  'DBtype',
53  'DBuser',
54  'DBWindowsAuthentication',
55  'DebugDumpSql',
56  'DebugLogFile',
57  'ExternalServers',
58  'SQLiteDataDir',
59  'SQLMode',
60  ];
61 
72  public static function applyDefaultConfig(
73  array $lbConf,
74  ServiceOptions $options,
75  ConfiguredReadOnlyMode $readOnlyMode,
76  BagOStuff $srvCache,
77  BagOStuff $mainStash,
78  WANObjectCache $wanCache
79  ) {
80  $options->assertRequiredOptions( self::APPLY_DEFAULT_CONFIG_OPTIONS );
81 
82  global $wgCommandLineMode;
83 
84  $typesWithSchema = self::getDbTypesWithSchemas();
85 
86  $lbConf += [
87  'localDomain' => new DatabaseDomain(
88  $options->get( 'DBname' ),
89  $options->get( 'DBmwschema' ),
90  $options->get( 'DBprefix' )
91  ),
92  'profiler' => function ( $section ) {
93  return Profiler::instance()->scopedProfileIn( $section );
94  },
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' ),
106  ];
107 
108  $serversCheck = [];
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 );
119  }
120  } else {
121  $server = self::initServerInfo(
122  [
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' ),
128  'load' => 1
129  ],
130  $options
131  );
132 
133  $server['flags'] |= $options->get( 'DBssl' ) ? DBO_SSL : 0;
134  $server['flags'] |= $options->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
135 
136  $lbConf['servers'] = [ $server ];
137  }
138  if ( !isset( $lbConf['externalClusters'] ) ) {
139  $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
140  }
141 
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' );
147  }
148  $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
149  }
150  $serversCheck = [ $lbConf['serverTemplate'] ] ?? [];
151  }
152 
153  self::assertValidServerConfigs(
154  $serversCheck,
155  $options->get( 'DBname' ),
156  $options->get( 'DBprefix' )
157  );
158 
159  $lbConf = self::injectObjectCaches( $lbConf, $srvCache, $mainStash, $wanCache );
160 
161  return $lbConf;
162  }
163 
167  private static function getDbTypesWithSchemas() {
168  return [ 'postgres' ];
169  }
170 
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' ] );
183  $server += [
184  'dbDirectory' => $options->get( 'SQLiteDataDir' ),
185  'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
186  ];
187  } elseif ( $server['type'] === 'postgres' ) {
188  $server += [
189  'port' => $options->get( 'DBport' ),
190  // Work around the reserved word usage in MediaWiki schema
191  'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
192  ];
193  }
194 
195  if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
196  $server += [ 'schema' => $options->get( 'DBmwschema' ) ];
197  }
198 
199  $flags = $server['flags'] ?? DBO_DEFAULT;
200  if ( $options->get( 'DebugDumpSql' ) || $options->get( 'DebugLogFile' ) ) {
201  $flags |= DBO_DEBUG;
202  }
203  $server['flags'] = $flags;
204 
205  $server += [
206  'tablePrefix' => $options->get( 'DBprefix' ),
207  'sqlMode' => $options->get( 'SQLMode' ),
208  ];
209 
210  return $server;
211  }
212 
220  private static function injectObjectCaches(
221  array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
222  ) {
223  // Fallback if APC style caching is not an option
224  if ( $sCache instanceof EmptyBagOStuff ) {
225  $sCache = new HashBagOStuff( [ 'maxKeys' => 100 ] );
226  }
227 
228  // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
229  if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
230  $lbConf['srvCache'] = $sCache;
231  }
232  if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
233  $lbConf['memStash'] = $mStash;
234  }
235  if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
236  $lbConf['wanCache'] = $wCache;
237  }
238 
239  return $lbConf;
240  }
241 
247  private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
248  foreach ( $servers as $server ) {
249  $type = $server['type'] ?? null;
250  $srvDB = $server['dbname'] ?? null; // server DB
251  $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
252 
253  if ( $type === 'mysql' ) {
254  // A DB name is not needed to connect to mysql; 'dbname' is useless.
255  // This field only defines the DB to use for unspecified DB domains.
256  if ( $srvDB !== null && $srvDB !== $ldDB ) {
257  self::reportMismatchedDBs( $srvDB, $ldDB );
258  }
259  } elseif ( $type === 'postgres' ) {
260  if ( $srvTP !== '' ) {
261  self::reportIfPrefixSet( $srvTP, $type );
262  }
263  }
264 
265  if ( $srvTP !== '' && $srvTP !== $ldTP ) {
266  self::reportMismatchedPrefixes( $srvTP, $ldTP );
267  }
268  }
269  }
270 
275  private static function reportIfPrefixSet( $prefix, $dbType ) {
276  $e = new UnexpectedValueException(
277  "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
278  "MediaWiki does not support using a table prefix with this RDBMS type."
279  );
281  exit;
282  }
283 
288  private static function reportMismatchedDBs( $srvDB, $ldDB ) {
289  $e = new UnexpectedValueException(
290  "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
291  "Set \$wgDBname to the database used by this wiki project. " .
292  "There is rarely a need to set 'dbname' in \$wgDBservers. " .
293  "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
294  "use of Database::getDomainId(), and other features are not reliable when " .
295  "\$wgDBservers does not match the local wiki database/prefix."
296  );
298  exit;
299  }
300 
305  private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
306  $e = new UnexpectedValueException(
307  "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
308  "Set \$wgDBprefix to the table prefix used by this wiki project. " .
309  "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
310  "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
311  "use of Database::getDomainId(), and other features are not reliable when " .
312  "\$wgDBservers does not match the local wiki database/prefix."
313  );
315  exit;
316  }
317 
327  public static function getLBFactoryClass( array $config ) {
328  // For configuration backward compatibility after removing
329  // underscores from class names in MediaWiki 1.23.
330  $bcClasses = [
331  'LBFactory_Simple' => 'LBFactorySimple',
332  'LBFactory_Single' => 'LBFactorySingle',
333  'LBFactory_Multi' => 'LBFactoryMulti'
334  ];
335 
336  $class = $config['class'];
337 
338  if ( isset( $bcClasses[$class] ) ) {
339  $class = $bcClasses[$class];
340  wfDeprecated(
341  '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
342  '1.23'
343  );
344  }
345 
346  // For configuration backward compatibility after moving classes to namespaces (1.29)
347  $compat = [
348  'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
349  'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
350  'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
351  ];
352 
353  if ( isset( $compat[$class] ) ) {
354  $class = $compat[$class];
355  }
356 
357  return $class;
358  }
359 
365  public static function logDeprecation( $msg ) {
366  global $wgDevelopmentWarnings;
367 
368  if ( isset( self::$loggedDeprecations[$msg] ) ) {
369  return;
370  }
371  self::$loggedDeprecations[$msg] = true;
372 
373  if ( $wgDevelopmentWarnings ) {
374  trigger_error( $msg, E_USER_DEPRECATED );
375  }
376  wfDebugLog( 'deprecated', $msg, 'private' );
377  }
378 }
static instance()
Singleton.
Definition: Profiler.php:63
wfHostname()
Fetch server name for use in error reporting etc.
static getDbTypesWithSchemas()
A read-only mode service which does not depend on LoadBalancer.
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)
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:35
static injectObjectCaches(array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache)
static applyDefaultConfig(array $lbConf, ServiceOptions $options, ConfiguredReadOnlyMode $readOnlyMode, BagOStuff $srvCache, BagOStuff $mainStash, WANObjectCache $wanCache)
Definition: MWLBFactory.php:72
getQoS( $flag)
Definition: BagOStuff.php:467
static output( $e, $mode, $eNew=null)
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.
const DBO_DEFAULT
Definition: defines.php:13
Class to handle database/schema/prefix specifications for IDatabase.
static reportIfPrefixSet( $prefix, $dbType)
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-specific class for generating database load balancers.
Definition: MWLBFactory.php:32
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