MediaWiki master
MWLBFactory.php
Go to the documentation of this file.
1<?php
24use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
37use Wikimedia\RequestTimeout\CriticalSectionProvider;
38
46
48 private static $loggedDeprecations = [];
49
50 public const CORE_VIRTUAL_DOMAINS = [ 'virtual-botpasswords' ];
51
56 MainConfigNames::DBcompress,
57 MainConfigNames::DBDefaultGroup,
58 MainConfigNames::DBmwschema,
59 MainConfigNames::DBname,
60 MainConfigNames::DBpassword,
61 MainConfigNames::DBport,
62 MainConfigNames::DBprefix,
63 MainConfigNames::DBserver,
64 MainConfigNames::DBservers,
65 MainConfigNames::DBssl,
66 MainConfigNames::DBStrictWarnings,
67 MainConfigNames::DBtype,
68 MainConfigNames::DBuser,
69 MainConfigNames::DebugDumpSql,
70 MainConfigNames::DebugLogFile,
71 MainConfigNames::DebugToolbar,
72 MainConfigNames::ExternalServers,
73 MainConfigNames::SQLiteDataDir,
74 MainConfigNames::SQLMode,
75 MainConfigNames::VirtualDomainsMapping,
76 ];
80 private $options;
84 private $readOnlyMode;
88 private $chronologyProtector;
92 private $srvCache;
96 private $wanCache;
100 private $csProvider;
104 private $statsdDataFactory;
106 private array $virtualDomains;
107
118 public function __construct(
119 ServiceOptions $options,
120 ConfiguredReadOnlyMode $readOnlyMode,
121 ChronologyProtector $chronologyProtector,
122 BagOStuff $srvCache,
123 WANObjectCache $wanCache,
124 CriticalSectionProvider $csProvider,
125 StatsdDataFactoryInterface $statsdDataFactory,
126 array $virtualDomains
127 ) {
128 $this->options = $options;
129 $this->readOnlyMode = $readOnlyMode;
130 $this->chronologyProtector = $chronologyProtector;
131 $this->srvCache = $srvCache;
132 $this->wanCache = $wanCache;
133 $this->csProvider = $csProvider;
134 $this->statsdDataFactory = $statsdDataFactory;
135 $this->virtualDomains = $virtualDomains;
136 }
137
143 public function applyDefaultConfig( array $lbConf ) {
144 $this->options->assertRequiredOptions( self::APPLY_DEFAULT_CONFIG_OPTIONS );
145
146 $typesWithSchema = self::getDbTypesWithSchemas();
147 if ( Profiler::instance() instanceof ProfilerStub ) {
148 $profilerCallback = null;
149 } else {
150 $profilerCallback = static function ( $section ) {
151 return Profiler::instance()->scopedProfileIn( $section );
152 };
153 }
154
155 $lbConf += [
156 'localDomain' => new DatabaseDomain(
157 $this->options->get( MainConfigNames::DBname ),
158 $this->options->get( MainConfigNames::DBmwschema ),
159 $this->options->get( MainConfigNames::DBprefix )
160 ),
161 'profiler' => $profilerCallback,
162 'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
163 'logger' => LoggerFactory::getInstance( 'rdbms' ),
164 'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
165 'deprecationLogger' => [ static::class, 'logDeprecation' ],
166 'statsdDataFactory' => $this->statsdDataFactory,
167 'cliMode' => MW_ENTRY_POINT === 'cli',
168 'readOnlyReason' => $this->readOnlyMode->getReason(),
169 'defaultGroup' => $this->options->get( MainConfigNames::DBDefaultGroup ),
170 'criticalSectionProvider' => $this->csProvider
171 ];
172
173 $serversCheck = [];
174 // When making changes here, remember to also specify MediaWiki-specific options
175 // for Database classes in the relevant Installer subclass.
176 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
177 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
178 if ( isset( $lbConf['servers'] ) ) {
179 // Server array is already explicitly configured
180 } elseif ( is_array( $this->options->get( MainConfigNames::DBservers ) ) ) {
181 $lbConf['servers'] = [];
182 foreach ( $this->options->get( MainConfigNames::DBservers ) as $i => $server ) {
183 $lbConf['servers'][$i] = self::initServerInfo( $server, $this->options );
184 }
185 } else {
186 $server = self::initServerInfo(
187 [
188 'host' => $this->options->get( MainConfigNames::DBserver ),
189 'user' => $this->options->get( MainConfigNames::DBuser ),
190 'password' => $this->options->get( MainConfigNames::DBpassword ),
191 'dbname' => $this->options->get( MainConfigNames::DBname ),
192 'type' => $this->options->get( MainConfigNames::DBtype ),
193 'load' => 1
194 ],
195 $this->options
196 );
197
198 if ( $this->options->get( MainConfigNames::DBssl ) ) {
199 $server['ssl'] = true;
200 }
201 $server['flags'] |= $this->options->get( MainConfigNames::DBcompress ) ? DBO_COMPRESS : 0;
202 if ( $this->options->get( MainConfigNames::DBStrictWarnings ) ) {
203 $server['strictWarnings'] = true;
204 }
205
206 $lbConf['servers'] = [ $server ];
207 }
208 if ( !isset( $lbConf['externalClusters'] ) ) {
209 $lbConf['externalClusters'] = $this->options->get( MainConfigNames::ExternalServers );
210 }
211
212 $serversCheck = $lbConf['servers'];
213 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
214 if ( isset( $lbConf['serverTemplate'] ) ) {
215 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
216 $lbConf['serverTemplate']['schema'] = $this->options->get( MainConfigNames::DBmwschema );
217 }
218 $lbConf['serverTemplate']['sqlMode'] = $this->options->get( MainConfigNames::SQLMode );
219 $serversCheck = [ $lbConf['serverTemplate'] ];
220 }
221 }
222
223 self::assertValidServerConfigs(
224 $serversCheck,
225 $this->options->get( MainConfigNames::DBname ),
226 $this->options->get( MainConfigNames::DBprefix )
227 );
228
229 $lbConf['chronologyProtector'] = $this->chronologyProtector;
230 $lbConf['srvCache'] = $this->srvCache;
231 $lbConf['wanCache'] = $this->wanCache;
232 $lbConf['virtualDomains'] = array_merge( $this->virtualDomains, self::CORE_VIRTUAL_DOMAINS );
233 $lbConf['virtualDomainsMapping'] = $this->options->get( MainConfigNames::VirtualDomainsMapping );
234
235 return $lbConf;
236 }
237
241 private function getDbTypesWithSchemas() {
242 return [ 'postgres' ];
243 }
244
250 private function initServerInfo( array $server, ServiceOptions $options ) {
251 if ( $server['type'] === 'sqlite' ) {
252 $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
253 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
254 // See https://www.sqlite.org/lang_transaction.html
255 // See https://www.sqlite.org/lockingv3.html#shared_lock
256 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
257 if ( MW_ENTRY_POINT === 'rest' && !$isHttpRead ) {
258 // Hack to support some re-entrant invocations using sqlite
259 // See: T259685, T91820
260 $request = \MediaWiki\Rest\EntryPoint::getMainRequest();
261 if ( $request->hasHeader( 'Promise-Non-Write-API-Action' ) ) {
262 $isHttpRead = true;
263 }
264 }
265 $server += [
266 'dbDirectory' => $options->get( MainConfigNames::SQLiteDataDir ),
267 'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
268 ];
269 } elseif ( $server['type'] === 'postgres' ) {
270 $server += [ 'port' => $options->get( MainConfigNames::DBport ) ];
271 }
272
273 if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
274 $server += [ 'schema' => $options->get( MainConfigNames::DBmwschema ) ];
275 }
276
277 $flags = $server['flags'] ?? DBO_DEFAULT;
278 if ( $options->get( MainConfigNames::DebugDumpSql )
279 || $options->get( MainConfigNames::DebugLogFile )
280 || $options->get( MainConfigNames::DebugToolbar )
281 ) {
282 $flags |= DBO_DEBUG;
283 }
284 $server['flags'] = $flags;
285
286 $server += [
287 'tablePrefix' => $options->get( MainConfigNames::DBprefix ),
288 'sqlMode' => $options->get( MainConfigNames::SQLMode ),
289 ];
290
291 return $server;
292 }
293
299 private function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
300 foreach ( $servers as $server ) {
301 $type = $server['type'] ?? null;
302 $srvDB = $server['dbname'] ?? null; // server DB
303 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
304
305 if ( $type === 'mysql' ) {
306 // A DB name is not needed to connect to mysql; 'dbname' is useless.
307 // This field only defines the DB to use for unspecified DB domains.
308 if ( $srvDB !== null && $srvDB !== $ldDB ) {
309 self::reportMismatchedDBs( $srvDB, $ldDB );
310 }
311 } elseif ( $type === 'postgres' ) {
312 if ( $srvTP !== '' ) {
313 self::reportIfPrefixSet( $srvTP, $type );
314 }
315 }
316
317 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
318 self::reportMismatchedPrefixes( $srvTP, $ldTP );
319 }
320 }
321 }
322
328 private function reportIfPrefixSet( $prefix, $dbType ) {
329 $e = new UnexpectedValueException(
330 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
331 "MediaWiki does not support using a table prefix with this RDBMS type."
332 );
333 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
334 exit;
335 }
336
342 private function reportMismatchedDBs( $srvDB, $ldDB ) {
343 $e = new UnexpectedValueException(
344 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
345 "Set \$wgDBname to the database used by this wiki project. " .
346 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
347 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
348 "use of Database::getDomainId(), and other features are not reliable when " .
349 "\$wgDBservers does not match the local wiki database/prefix."
350 );
351 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
352 exit;
353 }
354
360 private function reportMismatchedPrefixes( $srvTP, $ldTP ) {
361 $e = new UnexpectedValueException(
362 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
363 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
364 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
365 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
366 "use of Database::getDomainId(), and other features are not reliable when " .
367 "\$wgDBservers does not match the local wiki database/prefix."
368 );
369 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
370 exit;
371 }
372
380 public function getLBFactoryClass( array $config ) {
381 $compat = [
382 // For LocalSettings.php compat after removing underscores (since 1.23).
383 'LBFactory_Single' => Wikimedia\Rdbms\LBFactorySingle::class,
384 'LBFactory_Simple' => Wikimedia\Rdbms\LBFactorySimple::class,
385 'LBFactory_Multi' => Wikimedia\Rdbms\LBFactoryMulti::class,
386 // For LocalSettings.php compat after moving classes to namespaces (since 1.29).
387 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
388 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
389 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
390 ];
391
392 $class = $config['class'];
393 return $compat[$class] ?? $class;
394 }
395
399 public function setDomainAliases( ILBFactory $lbFactory ) {
400 $domain = DatabaseDomain::newFromId( $lbFactory->getLocalDomainID() );
401 // For compatibility with hyphenated $wgDBname values on older wikis, handle callers
402 // that assume corresponding database domain IDs and wiki IDs have identical values
403 $rawLocalDomain = strlen( $domain->getTablePrefix() )
404 ? "{$domain->getDatabase()}-{$domain->getTablePrefix()}"
405 : (string)$domain->getDatabase();
406
407 $lbFactory->setDomainAliases( [ $rawLocalDomain => $domain ] );
408 }
409
433 public function applyGlobalState(
434 ILBFactory $lbFactory,
435 Config $config,
437 ): void {
438 if ( MW_ENTRY_POINT === 'cli' ) {
439 $lbFactory->getMainLB()->setTransactionListener(
440 __METHOD__,
441 static function ( $trigger ) use ( $stats, $config ) {
442 // During maintenance scripts and PHPUnit integration tests, we let
443 // DeferredUpdates run immediately from addUpdate(), unless a transaction
444 // is active. Notify DeferredUpdates after any commit to try now.
445 // See DeferredUpdates::tryOpportunisticExecute for why.
446 if ( $trigger === IDatabase::TRIGGER_COMMIT ) {
447 DeferredUpdates::tryOpportunisticExecute();
448 }
449 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
450 MediaWiki::emitBufferedStatsdData( $stats, $config );
451 }
452 );
454 __METHOD__,
455 static function () use ( $stats, $config ) {
456 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
457 MediaWiki::emitBufferedStatsdData( $stats, $config );
458 }
459 );
460
461 }
462 }
463
469 public static function logDeprecation( $msg ) {
470 if ( isset( self::$loggedDeprecations[$msg] ) ) {
471 return;
472 }
473 self::$loggedDeprecations[$msg] = true;
474 MWDebug::sendRawDeprecated( $msg, true, wfGetCaller() );
475 }
476}
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
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.
Debug toolbar.
Definition MWDebug.php:48
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.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:88
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:39
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