MediaWiki 1.41.2
MWLBFactory.php
Go to the documentation of this file.
1<?php
24use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
34use Wikimedia\RequestTimeout\CriticalSectionProvider;
35
43
45 private static $loggedDeprecations = [];
46
51 'CommandLineMode',
52 MainConfigNames::DBcompress,
53 MainConfigNames::DBDefaultGroup,
54 MainConfigNames::DBmwschema,
55 MainConfigNames::DBname,
56 MainConfigNames::DBpassword,
57 MainConfigNames::DBport,
58 MainConfigNames::DBprefix,
59 MainConfigNames::DBserver,
60 MainConfigNames::DBservers,
61 MainConfigNames::DBssl,
62 MainConfigNames::DBtype,
63 MainConfigNames::DBuser,
64 MainConfigNames::DebugDumpSql,
65 MainConfigNames::DebugLogFile,
66 MainConfigNames::DebugToolbar,
67 MainConfigNames::ExternalServers,
68 MainConfigNames::SQLiteDataDir,
69 MainConfigNames::SQLMode,
70 MainConfigNames::VirtualDomainsMapping,
71 ];
75 private $options;
79 private $readOnlyMode;
83 private $chronologyProtector;
87 private $srvCache;
91 private $wanCache;
95 private $csProvider;
99 private $statsdDataFactory;
100 private array $virtualDomains = [];
101
111 public function __construct(
112 ServiceOptions $options,
113 ConfiguredReadOnlyMode $readOnlyMode,
114 ChronologyProtector $chronologyProtector,
115 BagOStuff $srvCache,
116 WANObjectCache $wanCache,
117 CriticalSectionProvider $csProvider,
118 StatsdDataFactoryInterface $statsdDataFactory,
119 array $virtualDomains
120 ) {
121 $this->options = $options;
122 $this->readOnlyMode = $readOnlyMode;
123 $this->chronologyProtector = $chronologyProtector;
124 $this->srvCache = $srvCache;
125 $this->wanCache = $wanCache;
126 $this->csProvider = $csProvider;
127 $this->statsdDataFactory = $statsdDataFactory;
128 $this->virtualDomains = $virtualDomains;
129 }
130
136 public function applyDefaultConfig( array $lbConf ) {
137 $this->options->assertRequiredOptions( self::APPLY_DEFAULT_CONFIG_OPTIONS );
138
139 $typesWithSchema = self::getDbTypesWithSchemas();
140 if ( Profiler::instance() instanceof ProfilerStub ) {
141 $profilerCallback = null;
142 } else {
143 $profilerCallback = static function ( $section ) {
144 return Profiler::instance()->scopedProfileIn( $section );
145 };
146 }
147
148 $lbConf += [
149 'localDomain' => new DatabaseDomain(
150 $this->options->get( MainConfigNames::DBname ),
151 $this->options->get( MainConfigNames::DBmwschema ),
152 $this->options->get( MainConfigNames::DBprefix )
153 ),
154 'profiler' => $profilerCallback,
155 'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
156 'logger' => LoggerFactory::getInstance( 'rdbms' ),
157 'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
158 'deprecationLogger' => [ static::class, 'logDeprecation' ],
159 'statsdDataFactory' => $this->statsdDataFactory,
160 'cliMode' => $this->options->get( 'CommandLineMode' ),
161 'readOnlyReason' => $this->readOnlyMode->getReason(),
162 'defaultGroup' => $this->options->get( MainConfigNames::DBDefaultGroup ),
163 'criticalSectionProvider' => $this->csProvider
164 ];
165
166 $serversCheck = [];
167 // When making changes here, remember to also specify MediaWiki-specific options
168 // for Database classes in the relevant Installer subclass.
169 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
170 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
171 if ( isset( $lbConf['servers'] ) ) {
172 // Server array is already explicitly configured
173 } elseif ( is_array( $this->options->get( MainConfigNames::DBservers ) ) ) {
174 $lbConf['servers'] = [];
175 foreach ( $this->options->get( MainConfigNames::DBservers ) as $i => $server ) {
176 $lbConf['servers'][$i] = self::initServerInfo( $server, $this->options );
177 }
178 } else {
179 $server = self::initServerInfo(
180 [
181 'host' => $this->options->get( MainConfigNames::DBserver ),
182 'user' => $this->options->get( MainConfigNames::DBuser ),
183 'password' => $this->options->get( MainConfigNames::DBpassword ),
184 'dbname' => $this->options->get( MainConfigNames::DBname ),
185 'type' => $this->options->get( MainConfigNames::DBtype ),
186 'load' => 1
187 ],
188 $this->options
189 );
190
191 if ( $this->options->get( MainConfigNames::DBssl ) ) {
192 $server['ssl'] = true;
193 }
194 $server['flags'] |= $this->options->get( MainConfigNames::DBcompress ) ? DBO_COMPRESS : 0;
195
196 $lbConf['servers'] = [ $server ];
197 }
198 if ( !isset( $lbConf['externalClusters'] ) ) {
199 $lbConf['externalClusters'] = $this->options->get( MainConfigNames::ExternalServers );
200 }
201
202 $serversCheck = $lbConf['servers'];
203 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
204 if ( isset( $lbConf['serverTemplate'] ) ) {
205 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
206 $lbConf['serverTemplate']['schema'] = $this->options->get( MainConfigNames::DBmwschema );
207 }
208 $lbConf['serverTemplate']['sqlMode'] = $this->options->get( MainConfigNames::SQLMode );
209 $serversCheck = [ $lbConf['serverTemplate'] ];
210 }
211 }
212
213 self::assertValidServerConfigs(
214 $serversCheck,
215 $this->options->get( MainConfigNames::DBname ),
216 $this->options->get( MainConfigNames::DBprefix )
217 );
218
219 $lbConf['chronologyProtector'] = $this->chronologyProtector;
220 $lbConf['srvCache'] = $this->srvCache;
221 $lbConf['wanCache'] = $this->wanCache;
222 $lbConf['virtualDomains'] = $this->virtualDomains;
223 $lbConf['virtualDomainsMapping'] = $this->options->get( MainConfigNames::VirtualDomainsMapping );
224
225 return $lbConf;
226 }
227
231 private function getDbTypesWithSchemas() {
232 return [ 'postgres' ];
233 }
234
240 private function initServerInfo( array $server, ServiceOptions $options ) {
241 if ( $server['type'] === 'sqlite' ) {
242 $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
243 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
244 // See https://www.sqlite.org/lang_transaction.html
245 // See https://www.sqlite.org/lockingv3.html#shared_lock
246 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
247 if ( MW_ENTRY_POINT === 'rest' && !$isHttpRead ) {
248 // Hack to support some re-entrant invocations using sqlite
249 // See: T259685, T91820
250 $request = \MediaWiki\Rest\EntryPoint::getMainRequest();
251 if ( $request->hasHeader( 'Promise-Non-Write-API-Action' ) ) {
252 $isHttpRead = true;
253 }
254 }
255 $server += [
256 'dbDirectory' => $options->get( MainConfigNames::SQLiteDataDir ),
257 'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
258 ];
259 } elseif ( $server['type'] === 'postgres' ) {
260 $server += [ 'port' => $options->get( MainConfigNames::DBport ) ];
261 }
262
263 if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
264 $server += [ 'schema' => $options->get( MainConfigNames::DBmwschema ) ];
265 }
266
267 $flags = $server['flags'] ?? DBO_DEFAULT;
268 if ( $options->get( MainConfigNames::DebugDumpSql )
269 || $options->get( MainConfigNames::DebugLogFile )
270 || $options->get( MainConfigNames::DebugToolbar )
271 ) {
272 $flags |= DBO_DEBUG;
273 }
274 $server['flags'] = $flags;
275
276 $server += [
277 'tablePrefix' => $options->get( MainConfigNames::DBprefix ),
278 'sqlMode' => $options->get( MainConfigNames::SQLMode ),
279 ];
280
281 return $server;
282 }
283
289 private function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
290 foreach ( $servers as $server ) {
291 $type = $server['type'] ?? null;
292 $srvDB = $server['dbname'] ?? null; // server DB
293 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
294
295 if ( $type === 'mysql' ) {
296 // A DB name is not needed to connect to mysql; 'dbname' is useless.
297 // This field only defines the DB to use for unspecified DB domains.
298 if ( $srvDB !== null && $srvDB !== $ldDB ) {
299 self::reportMismatchedDBs( $srvDB, $ldDB );
300 }
301 } elseif ( $type === 'postgres' ) {
302 if ( $srvTP !== '' ) {
303 self::reportIfPrefixSet( $srvTP, $type );
304 }
305 }
306
307 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
308 self::reportMismatchedPrefixes( $srvTP, $ldTP );
309 }
310 }
311 }
312
318 private function reportIfPrefixSet( $prefix, $dbType ) {
319 $e = new UnexpectedValueException(
320 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
321 "MediaWiki does not support using a table prefix with this RDBMS type."
322 );
323 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
324 exit;
325 }
326
332 private function reportMismatchedDBs( $srvDB, $ldDB ) {
333 $e = new UnexpectedValueException(
334 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
335 "Set \$wgDBname to the database used by this wiki project. " .
336 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
337 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
338 "use of Database::getDomainId(), and other features are not reliable when " .
339 "\$wgDBservers does not match the local wiki database/prefix."
340 );
341 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
342 exit;
343 }
344
350 private function reportMismatchedPrefixes( $srvTP, $ldTP ) {
351 $e = new UnexpectedValueException(
352 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
353 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
354 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
355 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
356 "use of Database::getDomainId(), and other features are not reliable when " .
357 "\$wgDBservers does not match the local wiki database/prefix."
358 );
359 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
360 exit;
361 }
362
370 public function getLBFactoryClass( array $config ) {
371 $compat = [
372 // For LocalSettings.php compat after removing underscores (since 1.23).
373 'LBFactory_Single' => Wikimedia\Rdbms\LBFactorySingle::class,
374 'LBFactory_Simple' => Wikimedia\Rdbms\LBFactorySimple::class,
375 'LBFactory_Multi' => Wikimedia\Rdbms\LBFactoryMulti::class,
376 // For LocalSettings.php compat after moving classes to namespaces (since 1.29).
377 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
378 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
379 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
380 ];
381
382 $class = $config['class'];
383 return $compat[$class] ?? $class;
384 }
385
389 public function setDomainAliases( ILBFactory $lbFactory ) {
390 $domain = DatabaseDomain::newFromId( $lbFactory->getLocalDomainID() );
391 // For compatibility with hyphenated $wgDBname values on older wikis, handle callers
392 // that assume corresponding database domain IDs and wiki IDs have identical values
393 $rawLocalDomain = strlen( $domain->getTablePrefix() )
394 ? "{$domain->getDatabase()}-{$domain->getTablePrefix()}"
395 : (string)$domain->getDatabase();
396
397 $lbFactory->setDomainAliases( [ $rawLocalDomain => $domain ] );
398 }
399
423 public function applyGlobalState(
424 ILBFactory $lbFactory,
425 Config $config,
427 ): void {
428 if ( $config->get( 'CommandLineMode' ) ) {
429 $lbFactory->getMainLB()->setTransactionListener(
430 __METHOD__,
431 static function ( $trigger ) use ( $stats, $config ) {
432 // During maintenance scripts and PHPUnit integration tests, we let
433 // DeferredUpdates run immediately from addUpdate(), unless a transaction
434 // is active. Notify DeferredUpdates after any commit to try now.
435 // See DeferredUpdates::tryOpportunisticExecute for why.
436 if ( $trigger === IDatabase::TRIGGER_COMMIT ) {
437 DeferredUpdates::tryOpportunisticExecute();
438 }
439 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
440 MediaWiki::emitBufferedStatsdData( $stats, $config );
441 }
442 );
444 __METHOD__,
445 static function () use ( $stats, $config ) {
446 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
447 MediaWiki::emitBufferedStatsdData( $stats, $config );
448 }
449 );
450
451 }
452 }
453
459 public static function logDeprecation( $msg ) {
460 if ( isset( self::$loggedDeprecations[$msg] ) ) {
461 return;
462 }
463 self::$loggedDeprecations[$msg] = true;
464 MWDebug::sendRawDeprecated( $msg, true, wfGetCaller() );
465 }
466}
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:88
const MW_ENTRY_POINT
Definition api.php:44
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)
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.
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