MediaWiki  master
MWLBFactory.php
Go to the documentation of this file.
1 <?php
28 
33 abstract class MWLBFactory {
34 
36  private static $loggedDeprecations = [];
37 
42  public const APPLY_DEFAULT_CONFIG_OPTIONS = [
43  'DBcompress',
44  'DBDefaultGroup',
45  'DBmwschema',
46  'DBname',
47  'DBpassword',
48  'DBport',
49  'DBprefix',
50  'DBserver',
51  'DBservers',
52  'DBssl',
53  'DBtype',
54  'DBuser',
55  'DebugDumpSql',
56  'DebugLogFile',
57  'DebugToolbar',
58  'ExternalServers',
59  'SQLiteDataDir',
60  'SQLMode',
61  ];
62 
73  public static function applyDefaultConfig(
74  array $lbConf,
75  ServiceOptions $options,
76  ConfiguredReadOnlyMode $readOnlyMode,
77  BagOStuff $srvCache,
78  BagOStuff $mainStash,
79  WANObjectCache $wanCache
80  ) {
81  $options->assertRequiredOptions( self::APPLY_DEFAULT_CONFIG_OPTIONS );
82 
83  global $wgCommandLineMode;
84 
85  $typesWithSchema = self::getDbTypesWithSchemas();
86 
87  $lbConf += [
88  'localDomain' => new DatabaseDomain(
89  $options->get( 'DBname' ),
90  $options->get( 'DBmwschema' ),
91  $options->get( 'DBprefix' )
92  ),
93  'profiler' => function ( $section ) {
94  return Profiler::instance()->scopedProfileIn( $section );
95  },
96  'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
97  'replLogger' => LoggerFactory::getInstance( 'DBReplication' ),
98  'queryLogger' => LoggerFactory::getInstance( 'DBQuery' ),
99  'connLogger' => LoggerFactory::getInstance( 'DBConnection' ),
100  'perfLogger' => LoggerFactory::getInstance( 'DBPerformance' ),
101  'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
102  'deprecationLogger' => [ static::class, 'logDeprecation' ],
103  'cliMode' => $wgCommandLineMode,
104  'hostname' => wfHostname(),
105  'readOnlyReason' => $readOnlyMode->getReason(),
106  'defaultGroup' => $options->get( 'DBDefaultGroup' ),
107  ];
108 
109  $serversCheck = [];
110  // When making changes here, remember to also specify MediaWiki-specific options
111  // for Database classes in the relevant Installer subclass.
112  // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
113  if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
114  if ( isset( $lbConf['servers'] ) ) {
115  // Server array is already explicitly configured
116  } elseif ( is_array( $options->get( 'DBservers' ) ) ) {
117  $lbConf['servers'] = [];
118  foreach ( $options->get( 'DBservers' ) as $i => $server ) {
119  $lbConf['servers'][$i] = self::initServerInfo( $server, $options );
120  }
121  } else {
122  $server = self::initServerInfo(
123  [
124  'host' => $options->get( 'DBserver' ),
125  'user' => $options->get( 'DBuser' ),
126  'password' => $options->get( 'DBpassword' ),
127  'dbname' => $options->get( 'DBname' ),
128  'type' => $options->get( 'DBtype' ),
129  'load' => 1
130  ],
131  $options
132  );
133 
134  $server['flags'] |= $options->get( 'DBssl' ) ? DBO_SSL : 0;
135  $server['flags'] |= $options->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
136 
137  $lbConf['servers'] = [ $server ];
138  }
139  if ( !isset( $lbConf['externalClusters'] ) ) {
140  $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
141  }
142 
143  $serversCheck = $lbConf['servers'];
144  } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
145  if ( isset( $lbConf['serverTemplate'] ) ) {
146  if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
147  $lbConf['serverTemplate']['schema'] = $options->get( 'DBmwschema' );
148  }
149  $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
150  $serversCheck = [ $lbConf['serverTemplate'] ];
151  }
152  }
153 
155  $serversCheck,
156  $options->get( 'DBname' ),
157  $options->get( 'DBprefix' )
158  );
159 
160  $lbConf['srvCache'] = $srvCache;
161  $lbConf['memStash'] = $mainStash;
162  $lbConf['wanCache'] = $wanCache;
163 
164  return $lbConf;
165  }
166 
170  private static function getDbTypesWithSchemas() {
171  return [ 'postgres' ];
172  }
173 
179  private static function initServerInfo( array $server, ServiceOptions $options ) {
180  if ( $server['type'] === 'sqlite' ) {
181  $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
182  // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
183  // See https://www.sqlite.org/lang_transaction.html
184  // See https://www.sqlite.org/lockingv3.html#shared_lock
185  $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
186  $server += [
187  'dbDirectory' => $options->get( 'SQLiteDataDir' ),
188  'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
189  ];
190  } elseif ( $server['type'] === 'postgres' ) {
191  $server += [
192  'port' => $options->get( 'DBport' ),
193  // Work around the reserved word usage in MediaWiki schema
194  'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
195  ];
196  }
197 
198  if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
199  $server += [ 'schema' => $options->get( 'DBmwschema' ) ];
200  }
201 
202  $flags = $server['flags'] ?? DBO_DEFAULT;
203  if ( $options->get( 'DebugDumpSql' )
204  || $options->get( 'DebugLogFile' )
205  || $options->get( 'DebugToolbar' )
206  ) {
207  $flags |= DBO_DEBUG;
208  }
209  $server['flags'] = $flags;
210 
211  $server += [
212  'tablePrefix' => $options->get( 'DBprefix' ),
213  'sqlMode' => $options->get( 'SQLMode' ),
214  ];
215 
216  return $server;
217  }
218 
224  private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
225  foreach ( $servers as $server ) {
226  $type = $server['type'] ?? null;
227  $srvDB = $server['dbname'] ?? null; // server DB
228  $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
229 
230  if ( $type === 'mysql' ) {
231  // A DB name is not needed to connect to mysql; 'dbname' is useless.
232  // This field only defines the DB to use for unspecified DB domains.
233  if ( $srvDB !== null && $srvDB !== $ldDB ) {
234  self::reportMismatchedDBs( $srvDB, $ldDB );
235  }
236  } elseif ( $type === 'postgres' ) {
237  if ( $srvTP !== '' ) {
238  self::reportIfPrefixSet( $srvTP, $type );
239  }
240  }
241 
242  if ( $srvTP !== '' && $srvTP !== $ldTP ) {
243  self::reportMismatchedPrefixes( $srvTP, $ldTP );
244  }
245  }
246  }
247 
252  private static function reportIfPrefixSet( $prefix, $dbType ) {
253  $e = new UnexpectedValueException(
254  "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
255  "MediaWiki does not support using a table prefix with this RDBMS type."
256  );
258  exit;
259  }
260 
265  private static function reportMismatchedDBs( $srvDB, $ldDB ) {
266  $e = new UnexpectedValueException(
267  "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
268  "Set \$wgDBname to the database used by this wiki project. " .
269  "There is rarely a need to set 'dbname' in \$wgDBservers. " .
270  "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
271  "use of Database::getDomainId(), and other features are not reliable when " .
272  "\$wgDBservers does not match the local wiki database/prefix."
273  );
275  exit;
276  }
277 
282  private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
283  $e = new UnexpectedValueException(
284  "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
285  "Set \$wgDBprefix to the table prefix used by this wiki project. " .
286  "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
287  "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
288  "use of Database::getDomainId(), and other features are not reliable when " .
289  "\$wgDBservers does not match the local wiki database/prefix."
290  );
292  exit;
293  }
294 
302  public static function getLBFactoryClass( array $config ) {
303  $compat = [
304  // For LocalSettings.php compat after removing underscores (since 1.23).
305  'LBFactory_Single' => Wikimedia\Rdbms\LBFactorySingle::class,
306  'LBFactory_Simple' => Wikimedia\Rdbms\LBFactorySimple::class,
307  'LBFactory_Multi' => Wikimedia\Rdbms\LBFactoryMulti::class,
308  // For LocalSettings.php compat after moving classes to namespaces (since 1.29).
309  'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
310  'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
311  'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
312  ];
313 
314  $class = $config['class'];
315  return $compat[$class] ?? $class;
316  }
317 
321  public static function setDomainAliases( ILBFactory $lbFactory ) {
322  $domain = DatabaseDomain::newFromId( $lbFactory->getLocalDomainID() );
323  // For compatibility with hyphenated $wgDBname values on older wikis, handle callers
324  // that assume corresponding database domain IDs and wiki IDs have identical values
325  $rawLocalDomain = strlen( $domain->getTablePrefix() )
326  ? "{$domain->getDatabase()}-{$domain->getTablePrefix()}"
327  : (string)$domain->getDatabase();
328 
329  $lbFactory->setDomainAliases( [ $rawLocalDomain => $domain ] );
330  }
331 
337  public static function logDeprecation( $msg ) {
338  if ( isset( self::$loggedDeprecations[$msg] ) ) {
339  return;
340  }
341  self::$loggedDeprecations[$msg] = true;
342  MWDebug::sendRawDeprecated( $msg, true, wfGetCaller() );
343  }
344 }
MWLBFactory
MediaWiki-specific class for generating database load balancers.
Definition: MWLBFactory.php:33
Wikimedia\Rdbms\ILBFactory\getLocalDomainID
getLocalDomainID()
Get the local (and default) database domain ID of connection handles.
MWLBFactory\reportMismatchedDBs
static reportMismatchedDBs( $srvDB, $ldDB)
Definition: MWLBFactory.php:265
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:63
MWLBFactory\initServerInfo
static initServerInfo(array $server, ServiceOptions $options)
Definition: MWLBFactory.php:179
MWLBFactory\assertValidServerConfigs
static assertValidServerConfigs(array $servers, $ldDB, $ldTP)
Definition: MWLBFactory.php:224
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()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1285
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:70
DBO_SSL
const DBO_SSL
Definition: defines.php:17
MWLBFactory\logDeprecation
static logDeprecation( $msg)
Log a database deprecation warning.
Definition: MWLBFactory.php:337
MWLBFactory\setDomainAliases
static setDomainAliases(ILBFactory $lbFactory)
Definition: MWLBFactory.php:321
ConfiguredReadOnlyMode\getReason
getReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: ConfiguredReadOnlyMode.php:48
MWLBFactory\reportMismatchedPrefixes
static reportMismatchedPrefixes( $srvTP, $ldTP)
Definition: MWLBFactory.php:282
MWLBFactory\$loggedDeprecations
static array $loggedDeprecations
Cache of already-logged deprecation messages.
Definition: MWLBFactory.php:36
MediaWiki\Config\ServiceOptions
A class for passing options to services.
Definition: ServiceOptions.php:25
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
MWLBFactory\applyDefaultConfig
static applyDefaultConfig(array $lbConf, ServiceOptions $options, ConfiguredReadOnlyMode $readOnlyMode, BagOStuff $srvCache, BagOStuff $mainStash, WANObjectCache $wanCache)
Definition: MWLBFactory.php:73
MWExceptionRenderer\output
static output(Throwable $e, $mode, Throwable $eNew=null)
Definition: MWExceptionRenderer.php:40
MWLBFactory\getLBFactoryClass
static getLBFactoryClass(array $config)
Decide which LBFactory class to use.
Definition: MWLBFactory.php:302
MWExceptionRenderer\AS_PRETTY
const AS_PRETTY
Definition: MWExceptionRenderer.php:33
DBO_COMPRESS
const DBO_COMPRESS
Definition: defines.php:18
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:125
Wikimedia\Rdbms\ILBFactory\setDomainAliases
setDomainAliases(array $aliases)
Convert certain database domains to alternative ones.
Wikimedia
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
MediaWiki\Config\ServiceOptions\get
get( $key)
Definition: ServiceOptions.php:84
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/schema/prefix specifications for IDatabase.
Definition: DatabaseDomain.php:40
DBO_DEFAULT
const DBO_DEFAULT
Definition: defines.php:13
MWLBFactory\getDbTypesWithSchemas
static getDbTypesWithSchemas()
Definition: MWLBFactory.php:170
wfGetCaller
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Definition: GlobalFunctions.php:1393
MWDebug\sendRawDeprecated
static sendRawDeprecated( $msg, $sendToLog=true, $callerFunc='')
Send a raw deprecation message to the log and the debug toolbar, without filtering of duplicate messa...
Definition: MWDebug.php:319
MWLBFactory\reportIfPrefixSet
static reportIfPrefixSet( $prefix, $dbType)
Definition: MWLBFactory.php:252
MediaWiki\Config\ServiceOptions\assertRequiredOptions
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
Definition: ServiceOptions.php:62
Wikimedia\Rdbms\ILBFactory
An interface for generating database load balancers.
Definition: ILBFactory.php:33
$type
$type
Definition: testCompression.php:52