MediaWiki master
MWLBFactory.php
Go to the documentation of this file.
1<?php
24use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
35use Wikimedia\RequestTimeout\CriticalSectionProvider;
36
44
46 private static $loggedDeprecations = [];
47
48 public const CORE_VIRTUAL_DOMAINS = [ 'virtual-botpasswords' ];
49
54 MainConfigNames::DBcompress,
55 MainConfigNames::DBDefaultGroup,
56 MainConfigNames::DBmwschema,
57 MainConfigNames::DBname,
58 MainConfigNames::DBpassword,
59 MainConfigNames::DBport,
60 MainConfigNames::DBprefix,
61 MainConfigNames::DBserver,
62 MainConfigNames::DBservers,
63 MainConfigNames::DBssl,
64 MainConfigNames::DBStrictWarnings,
65 MainConfigNames::DBtype,
66 MainConfigNames::DBuser,
67 MainConfigNames::DebugDumpSql,
68 MainConfigNames::DebugLogFile,
69 MainConfigNames::DebugToolbar,
70 MainConfigNames::ExternalServers,
71 MainConfigNames::SQLiteDataDir,
72 MainConfigNames::SQLMode,
73 MainConfigNames::VirtualDomainsMapping,
74 ];
78 private $options;
82 private $readOnlyMode;
86 private $chronologyProtector;
90 private $srvCache;
94 private $wanCache;
98 private $csProvider;
102 private $statsdDataFactory;
104 private array $virtualDomains;
105
116 public function __construct(
117 ServiceOptions $options,
118 ConfiguredReadOnlyMode $readOnlyMode,
119 ChronologyProtector $chronologyProtector,
120 BagOStuff $srvCache,
121 WANObjectCache $wanCache,
122 CriticalSectionProvider $csProvider,
123 StatsdDataFactoryInterface $statsdDataFactory,
124 array $virtualDomains
125 ) {
126 $this->options = $options;
127 $this->readOnlyMode = $readOnlyMode;
128 $this->chronologyProtector = $chronologyProtector;
129 $this->srvCache = $srvCache;
130 $this->wanCache = $wanCache;
131 $this->csProvider = $csProvider;
132 $this->statsdDataFactory = $statsdDataFactory;
133 $this->virtualDomains = $virtualDomains;
134 }
135
141 public function applyDefaultConfig( array $lbConf ) {
142 $this->options->assertRequiredOptions( self::APPLY_DEFAULT_CONFIG_OPTIONS );
143
144 $typesWithSchema = self::getDbTypesWithSchemas();
145 if ( Profiler::instance() instanceof ProfilerStub ) {
146 $profilerCallback = null;
147 } else {
148 $profilerCallback = static function ( $section ) {
149 return Profiler::instance()->scopedProfileIn( $section );
150 };
151 }
152
153 $lbConf += [
154 'localDomain' => new DatabaseDomain(
155 $this->options->get( MainConfigNames::DBname ),
156 $this->options->get( MainConfigNames::DBmwschema ),
157 $this->options->get( MainConfigNames::DBprefix )
158 ),
159 'profiler' => $profilerCallback,
160 'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
161 'logger' => LoggerFactory::getInstance( 'rdbms' ),
162 'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
163 'deprecationLogger' => [ static::class, 'logDeprecation' ],
164 'statsdDataFactory' => $this->statsdDataFactory,
165 'cliMode' => MW_ENTRY_POINT === 'cli',
166 'readOnlyReason' => $this->readOnlyMode->getReason(),
167 'defaultGroup' => $this->options->get( MainConfigNames::DBDefaultGroup ),
168 'criticalSectionProvider' => $this->csProvider
169 ];
170
171 $serversCheck = [];
172 // When making changes here, remember to also specify MediaWiki-specific options
173 // for Database classes in the relevant Installer subclass.
174 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
175 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
176 if ( isset( $lbConf['servers'] ) ) {
177 // Server array is already explicitly configured
178 } elseif ( is_array( $this->options->get( MainConfigNames::DBservers ) ) ) {
179 $lbConf['servers'] = [];
180 foreach ( $this->options->get( MainConfigNames::DBservers ) as $i => $server ) {
181 $lbConf['servers'][$i] = self::initServerInfo( $server, $this->options );
182 }
183 } else {
184 $server = self::initServerInfo(
185 [
186 'host' => $this->options->get( MainConfigNames::DBserver ),
187 'user' => $this->options->get( MainConfigNames::DBuser ),
188 'password' => $this->options->get( MainConfigNames::DBpassword ),
189 'dbname' => $this->options->get( MainConfigNames::DBname ),
190 'type' => $this->options->get( MainConfigNames::DBtype ),
191 'load' => 1
192 ],
193 $this->options
194 );
195
196 if ( $this->options->get( MainConfigNames::DBssl ) ) {
197 $server['ssl'] = true;
198 }
199 $server['flags'] |= $this->options->get( MainConfigNames::DBcompress ) ? DBO_COMPRESS : 0;
200 if ( $this->options->get( MainConfigNames::DBStrictWarnings ) ) {
201 $server['strictWarnings'] = true;
202 }
203
204 $lbConf['servers'] = [ $server ];
205 }
206 if ( !isset( $lbConf['externalClusters'] ) ) {
207 $lbConf['externalClusters'] = $this->options->get( MainConfigNames::ExternalServers );
208 }
209
210 $serversCheck = $lbConf['servers'];
211 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
212 if ( isset( $lbConf['serverTemplate'] ) ) {
213 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
214 $lbConf['serverTemplate']['schema'] = $this->options->get( MainConfigNames::DBmwschema );
215 }
216 $lbConf['serverTemplate']['sqlMode'] = $this->options->get( MainConfigNames::SQLMode );
217 $serversCheck = [ $lbConf['serverTemplate'] ];
218 }
219 }
220
221 self::assertValidServerConfigs(
222 $serversCheck,
223 $this->options->get( MainConfigNames::DBname ),
224 $this->options->get( MainConfigNames::DBprefix )
225 );
226
227 $lbConf['chronologyProtector'] = $this->chronologyProtector;
228 $lbConf['srvCache'] = $this->srvCache;
229 $lbConf['wanCache'] = $this->wanCache;
230 $lbConf['virtualDomains'] = array_merge( $this->virtualDomains, self::CORE_VIRTUAL_DOMAINS );
231 $lbConf['virtualDomainsMapping'] = $this->options->get( MainConfigNames::VirtualDomainsMapping );
232
233 return $lbConf;
234 }
235
239 private function getDbTypesWithSchemas() {
240 return [ 'postgres' ];
241 }
242
248 private function initServerInfo( array $server, ServiceOptions $options ) {
249 if ( $server['type'] === 'sqlite' ) {
250 $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
251 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
252 // See https://www.sqlite.org/lang_transaction.html
253 // See https://www.sqlite.org/lockingv3.html#shared_lock
254 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
255 if ( MW_ENTRY_POINT === 'rest' && !$isHttpRead ) {
256 // Hack to support some re-entrant invocations using sqlite
257 // See: T259685, T91820
258 $request = \MediaWiki\Rest\EntryPoint::getMainRequest();
259 if ( $request->hasHeader( 'Promise-Non-Write-API-Action' ) ) {
260 $isHttpRead = true;
261 }
262 }
263 $server += [
264 'dbDirectory' => $options->get( MainConfigNames::SQLiteDataDir ),
265 'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
266 ];
267 } elseif ( $server['type'] === 'postgres' ) {
268 $server += [ 'port' => $options->get( MainConfigNames::DBport ) ];
269 }
270
271 if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
272 $server += [ 'schema' => $options->get( MainConfigNames::DBmwschema ) ];
273 }
274
275 $flags = $server['flags'] ?? DBO_DEFAULT;
276 if ( $options->get( MainConfigNames::DebugDumpSql )
277 || $options->get( MainConfigNames::DebugLogFile )
278 || $options->get( MainConfigNames::DebugToolbar )
279 ) {
280 $flags |= DBO_DEBUG;
281 }
282 $server['flags'] = $flags;
283
284 $server += [
285 'tablePrefix' => $options->get( MainConfigNames::DBprefix ),
286 'sqlMode' => $options->get( MainConfigNames::SQLMode ),
287 ];
288
289 return $server;
290 }
291
297 private function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
298 foreach ( $servers as $server ) {
299 $type = $server['type'] ?? null;
300 $srvDB = $server['dbname'] ?? null; // server DB
301 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
302
303 if ( $type === 'mysql' ) {
304 // A DB name is not needed to connect to mysql; 'dbname' is useless.
305 // This field only defines the DB to use for unspecified DB domains.
306 if ( $srvDB !== null && $srvDB !== $ldDB ) {
307 self::reportMismatchedDBs( $srvDB, $ldDB );
308 }
309 } elseif ( $type === 'postgres' ) {
310 if ( $srvTP !== '' ) {
311 self::reportIfPrefixSet( $srvTP, $type );
312 }
313 }
314
315 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
316 self::reportMismatchedPrefixes( $srvTP, $ldTP );
317 }
318 }
319 }
320
326 private function reportIfPrefixSet( $prefix, $dbType ) {
327 $e = new UnexpectedValueException(
328 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
329 "MediaWiki does not support using a table prefix with this RDBMS type."
330 );
331 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
332 exit;
333 }
334
340 private function reportMismatchedDBs( $srvDB, $ldDB ) {
341 $e = new UnexpectedValueException(
342 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
343 "Set \$wgDBname to the database used by this wiki project. " .
344 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
345 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
346 "use of Database::getDomainId(), and other features are not reliable when " .
347 "\$wgDBservers does not match the local wiki database/prefix."
348 );
349 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
350 exit;
351 }
352
358 private function reportMismatchedPrefixes( $srvTP, $ldTP ) {
359 $e = new UnexpectedValueException(
360 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
361 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
362 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
363 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
364 "use of Database::getDomainId(), and other features are not reliable when " .
365 "\$wgDBservers does not match the local wiki database/prefix."
366 );
367 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
368 exit;
369 }
370
378 public function getLBFactoryClass( array $config ) {
379 $compat = [
380 // For LocalSettings.php compat after removing underscores (since 1.23).
381 'LBFactory_Single' => Wikimedia\Rdbms\LBFactorySingle::class,
382 'LBFactory_Simple' => Wikimedia\Rdbms\LBFactorySimple::class,
383 'LBFactory_Multi' => Wikimedia\Rdbms\LBFactoryMulti::class,
384 // For LocalSettings.php compat after moving classes to namespaces (since 1.29).
385 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
386 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
387 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
388 ];
389
390 $class = $config['class'];
391 return $compat[$class] ?? $class;
392 }
393
397 public function setDomainAliases( ILBFactory $lbFactory ) {
398 $domain = DatabaseDomain::newFromId( $lbFactory->getLocalDomainID() );
399 // For compatibility with hyphenated $wgDBname values on older wikis, handle callers
400 // that assume corresponding database domain IDs and wiki IDs have identical values
401 $rawLocalDomain = strlen( $domain->getTablePrefix() )
402 ? "{$domain->getDatabase()}-{$domain->getTablePrefix()}"
403 : (string)$domain->getDatabase();
404
405 $lbFactory->setDomainAliases( [ $rawLocalDomain => $domain ] );
406 }
407
431 public function applyGlobalState(
432 ILBFactory $lbFactory,
433 Config $config,
435 ): void {
436 if ( MW_ENTRY_POINT === 'cli' ) {
437 $lbFactory->getMainLB()->setTransactionListener(
438 __METHOD__,
439 static function ( $trigger ) use ( $stats, $config ) {
440 // During maintenance scripts and PHPUnit integration tests, we let
441 // DeferredUpdates run immediately from addUpdate(), unless a transaction
442 // is active. Notify DeferredUpdates after any commit to try now.
443 // See DeferredUpdates::tryOpportunisticExecute for why.
444 if ( $trigger === IDatabase::TRIGGER_COMMIT ) {
445 DeferredUpdates::tryOpportunisticExecute();
446 }
447 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
448 MediaWiki::emitBufferedStatsdData( $stats, $config );
449 }
450 );
452 __METHOD__,
453 static function () use ( $stats, $config ) {
454 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
455 MediaWiki::emitBufferedStatsdData( $stats, $config );
456 }
457 );
458
459 }
460 }
461
467 public static function logDeprecation( $msg ) {
468 if ( isset( self::$loggedDeprecations[$msg] ) ) {
469 return;
470 }
471 self::$loggedDeprecations[$msg] = true;
472 MWDebug::sendRawDeprecated( $msg, true, wfGetCaller() );
473 }
474}
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
const MW_ENTRY_POINT
Definition api.php:35
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:85
static output(Throwable $e, $mode, Throwable $eNew=null)
MediaWiki-specific class for generating database load balancers.
__construct(ServiceOptions $options, ConfiguredReadOnlyMode $readOnlyMode, ChronologyProtector $chronologyProtector, BagOStuff $srvCache, WANObjectCache $wanCache, CriticalSectionProvider $csProvider, StatsdDataFactoryInterface $statsdDataFactory, array $virtualDomains)
static logDeprecation( $msg)
Log a database deprecation warning.
const APPLY_DEFAULT_CONFIG_OPTIONS
setDomainAliases(ILBFactory $lbFactory)
applyDefaultConfig(array $lbConf)
const CORE_VIRTUAL_DOMAINS
applyGlobalState(ILBFactory $lbFactory, Config $config, IBufferingStatsdDataFactory $stats)
Apply global state from the current web request or other PHP process.
getLBFactoryClass(array $config)
Decide which LBFactory class to use.
A class for passing options to services.
Defer callable updates to run later in the PHP process.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
Stub profiler that does nothing.
static instance()
Definition Profiler.php:105
Multi-datacenter aware caching interface.
Provide a given client with protection against visible database lag.
Determine whether a site is statically configured as read-only.
Class to handle database/schema/prefix specifications for IDatabase.
MediaWiki adaptation of StatsdDataFactory that provides buffering functionality.
Interface for configuration instances.
Definition Config.php:32
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:36
Manager of ILoadBalancer objects and, indirectly, IDatabase connections.
getLocalDomainID()
Get the local (and default) database domain ID of connection handles.
setDomainAliases(array $aliases)
Convert certain database domains to alternative ones.
getMainLB( $domain=false)
Get the tracked load balancer instance for the main cluster that handles the given domain.
setWaitForReplicationListener( $name, callable $callback=null)
Add a callback to be run in every call to waitForReplication() before waiting.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
const DBO_COMPRESS
Definition defines.php:19
const DBO_DEFAULT
Definition defines.php:13
const DBO_DEBUG
Definition defines.php:9