Debian Codegraph @

includes/db/MWLBFactory.php

raw symbols SCIP
1 <?php
2 /**
3 * Generator of database load balancing objects.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
25 use MediaWiki\Config\Config;
26 use MediaWiki\Config\ServiceOptions;
27 use MediaWiki\Debug\MWDebug;
28 use MediaWiki\Deferred\DeferredUpdates;
29 use MediaWiki\Logger\LoggerFactory;
30 use MediaWiki\MainConfigNames;
31 use Wikimedia\ObjectCache\BagOStuff;
32 use Wikimedia\ObjectCache\WANObjectCache;
33 use Wikimedia\Rdbms\ChronologyProtector;
34 use Wikimedia\Rdbms\ConfiguredReadOnlyMode;
35 use Wikimedia\Rdbms\DatabaseDomain;
36 use Wikimedia\Rdbms\IDatabase;
37 use Wikimedia\Rdbms\ILBFactory;
38 use Wikimedia\RequestTimeout\CriticalSectionProvider;
39 use Wikimedia\Stats\IBufferingStatsdDataFactory;
40
41 /**
42 * MediaWiki-specific class for generating database load balancers
43 *
44 * @internal For use by core ServiceWiring only.
45 * @ingroup Database
46 */
47 class MWLBFactory {
48
49 /** Cache of already-logged deprecation messages */
50 private static array $loggedDeprecations = [];
51
52 public const CORE_VIRTUAL_DOMAINS = [ 'virtual-botpasswords' ];
53
54 /**
55 * @internal For use by ServiceWiring
56 */
57 public const APPLY_DEFAULT_CONFIG_OPTIONS = [
58 MainConfigNames::DBcompress,
59 MainConfigNames::DBDefaultGroup,
60 MainConfigNames::DBmwschema,
61 MainConfigNames::DBname,
62 MainConfigNames::DBpassword,
63 MainConfigNames::DBport,
64 MainConfigNames::DBprefix,
65 MainConfigNames::DBserver,
66 MainConfigNames::DBservers,
67 MainConfigNames::DBssl,
68 MainConfigNames::DBStrictWarnings,
69 MainConfigNames::DBtype,
70 MainConfigNames::DBuser,
71 MainConfigNames::DebugDumpSql,
72 MainConfigNames::DebugLogFile,
73 MainConfigNames::DebugToolbar,
74 MainConfigNames::ExternalServers,
75 MainConfigNames::SQLiteDataDir,
76 MainConfigNames::SQLMode,
77 MainConfigNames::VirtualDomainsMapping,
78 ];
79 private ServiceOptions $options;
80 private ConfiguredReadOnlyMode $readOnlyMode;
81 private ChronologyProtector $chronologyProtector;
82 private BagOStuff $srvCache;
83 private WANObjectCache $wanCache;
84 private CriticalSectionProvider $csProvider;
85 private StatsdDataFactoryInterface $statsdDataFactory;
86 /** @var string[] */
87 private array $virtualDomains;
88
89 /**
90 * @param ServiceOptions $options
91 * @param ConfiguredReadOnlyMode $readOnlyMode
92 * @param ChronologyProtector $chronologyProtector
93 * @param BagOStuff $srvCache
94 * @param WANObjectCache $wanCache
95 * @param CriticalSectionProvider $csProvider
96 * @param StatsdDataFactoryInterface $statsdDataFactory
97 * @param string[] $virtualDomains
98 */
99 public function __construct(
100 ServiceOptions $options,
101 ConfiguredReadOnlyMode $readOnlyMode,
102 ChronologyProtector $chronologyProtector,
103 BagOStuff $srvCache,
104 WANObjectCache $wanCache,
105 CriticalSectionProvider $csProvider,
106 StatsdDataFactoryInterface $statsdDataFactory,
107 array $virtualDomains
108 ) {
109 $this->options = $options;
110 $this->readOnlyMode = $readOnlyMode;
111 $this->chronologyProtector = $chronologyProtector;
112 $this->srvCache = $srvCache;
113 $this->wanCache = $wanCache;
114 $this->csProvider = $csProvider;
115 $this->statsdDataFactory = $statsdDataFactory;
116 $this->virtualDomains = $virtualDomains;
117 }
118
119 /**
120 * @param array $lbConf Config for LBFactory::__construct()
121 * @return array
122 * @internal For use with service wiring
123 */
124 public function applyDefaultConfig( array $lbConf ): array {
125 $this->options->assertRequiredOptions( self::APPLY_DEFAULT_CONFIG_OPTIONS );
126
127 $typesWithSchema = self::getDbTypesWithSchemas();
128 if ( Profiler::instance() instanceof ProfilerStub ) {
129 $profilerCallback = null;
130 } else {
131 $profilerCallback = static function ( $section ) {
132 return Profiler::instance()->scopedProfileIn( $section );
133 };
134 }
135
136 $lbConf += [
137 'localDomain' => new DatabaseDomain(
138 $this->options->get( MainConfigNames::DBname ),
139 $this->options->get( MainConfigNames::DBmwschema ),
140 $this->options->get( MainConfigNames::DBprefix )
141 ),
142 'profiler' => $profilerCallback,
143 'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
144 'logger' => LoggerFactory::getInstance( 'rdbms' ),
145 'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
146 'deprecationLogger' => [ static::class, 'logDeprecation' ],
147 'statsdDataFactory' => $this->statsdDataFactory,
148 'cliMode' => MW_ENTRY_POINT === 'cli',
149 'readOnlyReason' => $this->readOnlyMode->getReason(),
150 'defaultGroup' => $this->options->get( MainConfigNames::DBDefaultGroup ),
151 'criticalSectionProvider' => $this->csProvider
152 ];
153
154 $serversCheck = [];
155 // When making changes here, remember to also specify MediaWiki-specific options
156 // for Database classes in the relevant Installer subclass.
157 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
158 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
159 if ( isset( $lbConf['servers'] ) ) {
160 // Server array is already explicitly configured
161 } elseif ( is_array( $this->options->get( MainConfigNames::DBservers ) ) ) {
162 $lbConf['servers'] = [];
163 foreach ( $this->options->get( MainConfigNames::DBservers ) as $i => $server ) {
164 $lbConf['servers'][$i] = self::initServerInfo( $server, $this->options );
165 }
166 } else {
167 $server = self::initServerInfo(
168 [
169 'host' => $this->options->get( MainConfigNames::DBserver ),
170 'user' => $this->options->get( MainConfigNames::DBuser ),
171 'password' => $this->options->get( MainConfigNames::DBpassword ),
172 'dbname' => $this->options->get( MainConfigNames::DBname ),
173 'type' => $this->options->get( MainConfigNames::DBtype ),
174 'load' => 1
175 ],
176 $this->options
177 );
178
179 if ( $this->options->get( MainConfigNames::DBssl ) ) {
180 $server['ssl'] = true;
181 }
182 $server['flags'] |= $this->options->get( MainConfigNames::DBcompress ) ? DBO_COMPRESS : 0;
183 if ( $this->options->get( MainConfigNames::DBStrictWarnings ) ) {
184 $server['strictWarnings'] = true;
185 }
186
187 $lbConf['servers'] = [ $server ];
188 }
189 if ( !isset( $lbConf['externalClusters'] ) ) {
190 $lbConf['externalClusters'] = $this->options->get( MainConfigNames::ExternalServers );
191 }
192
193 $serversCheck = $lbConf['servers'];
194 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
195 if ( isset( $lbConf['serverTemplate'] ) ) {
196 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
197 $lbConf['serverTemplate']['schema'] = $this->options->get( MainConfigNames::DBmwschema );
198 }
199 $lbConf['serverTemplate']['sqlMode'] = $this->options->get( MainConfigNames::SQLMode );
200 $serversCheck = [ $lbConf['serverTemplate'] ];
201 }
202 }
203
204 self::assertValidServerConfigs(
205 $serversCheck,
206 $this->options->get( MainConfigNames::DBname ),
207 $this->options->get( MainConfigNames::DBprefix )
208 );
209
210 $lbConf['chronologyProtector'] = $this->chronologyProtector;
211 $lbConf['srvCache'] = $this->srvCache;
212 $lbConf['wanCache'] = $this->wanCache;
213 $lbConf['virtualDomains'] = array_merge( $this->virtualDomains, self::CORE_VIRTUAL_DOMAINS );
214 $lbConf['virtualDomainsMapping'] = $this->options->get( MainConfigNames::VirtualDomainsMapping );
215
216 return $lbConf;
217 }
218
219 /**
220 * @return array
221 */
222 private function getDbTypesWithSchemas(): array {
223 return [ 'postgres' ];
224 }
225
226 /**
227 * @param array $server
228 * @param ServiceOptions $options
229 * @return array
230 */
231 private function initServerInfo( array $server, ServiceOptions $options ): array {
232 if ( $server['type'] === 'sqlite' ) {
233 $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
234 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
235 // See https://www.sqlite.org/lang_transaction.html
236 // See https://www.sqlite.org/lockingv3.html#shared_lock
237 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
238 if ( MW_ENTRY_POINT === 'rest' && !$isHttpRead ) {
239 // Hack to support some re-entrant invocations using sqlite
240 // See: T259685, T91820
241 $request = \MediaWiki\Rest\EntryPoint::getMainRequest();
242 if ( $request->hasHeader( 'Promise-Non-Write-API-Action' ) ) {
243 $isHttpRead = true;
244 }
245 }
246 $server += [
247 'dbDirectory' => $options->get( MainConfigNames::SQLiteDataDir ),
248 'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
249 ];
250 } elseif ( $server['type'] === 'postgres' ) {
251 $server += [ 'port' => $options->get( MainConfigNames::DBport ) ];
252 }
253
254 if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
255 $server += [ 'schema' => $options->get( MainConfigNames::DBmwschema ) ];
256 }
257
258 $flags = $server['flags'] ?? DBO_DEFAULT;
259 if ( $options->get( MainConfigNames::DebugDumpSql )
260 || $options->get( MainConfigNames::DebugLogFile )
261 || $options->get( MainConfigNames::DebugToolbar )
262 ) {
263 $flags |= DBO_DEBUG;
264 }
265 $server['flags'] = $flags;
266
267 $server += [
268 'tablePrefix' => $options->get( MainConfigNames::DBprefix ),
269 'sqlMode' => $options->get( MainConfigNames::SQLMode ),
270 ];
271
272 return $server;
273 }
274
275 /**
276 * @param array $servers
277 * @param string $ldDB Local domain database name
278 * @param string $ldTP Local domain prefix
279 */
280 private function assertValidServerConfigs( array $servers, string $ldDB, string $ldTP ): void {
281 foreach ( $servers as $server ) {
282 $type = $server['type'] ?? null;
283 $srvDB = $server['dbname'] ?? null; // server DB
284 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
285
286 if ( $type === 'mysql' ) {
287 // A DB name is not needed to connect to mysql; 'dbname' is useless.
288 // This field only defines the DB to use for unspecified DB domains.
289 if ( $srvDB !== null && $srvDB !== $ldDB ) {
290 self::reportMismatchedDBs( $srvDB, $ldDB );
291 }
292 } elseif ( $type === 'postgres' ) {
293 if ( $srvTP !== '' ) {
294 self::reportIfPrefixSet( $srvTP, $type );
295 }
296 }
297
298 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
299 self::reportMismatchedPrefixes( $srvTP, $ldTP );
300 }
301 }
302 }
303
304 /**
305 * @param string $prefix Table prefix
306 * @param string $dbType Database type
307 * @return never
308 */
309 private function reportIfPrefixSet( string $prefix, string $dbType ) {
310 $e = new UnexpectedValueException(
311 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
312 "MediaWiki does not support using a table prefix with this RDBMS type."
313 );
314 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
315 exit;
316 }
317
318 /**
319 * @param string $srvDB Server config database
320 * @param string $ldDB Local DB domain database
321 * @return never
322 */
323 private function reportMismatchedDBs( string $srvDB, string $ldDB ) {
324 $e = new UnexpectedValueException(
325 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
326 "Set \$wgDBname to the database used by this wiki project. " .
327 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
328 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
329 "use of Database::getDomainId(), and other features are not reliable when " .
330 "\$wgDBservers does not match the local wiki database/prefix."
331 );
332 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
333 exit;
334 }
335
336 /**
337 * @param string $srvTP Server config table prefix
338 * @param string $ldTP Local DB domain database
339 * @return never
340 */
341 private function reportMismatchedPrefixes( string $srvTP, string $ldTP ) {
342 $e = new UnexpectedValueException(
343 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
344 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
345 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
346 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
347 "use of Database::getDomainId(), and other features are not reliable when " .
348 "\$wgDBservers does not match the local wiki database/prefix."
349 );
350 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW );
351 exit;
352 }
353
354 /**
355 * Decide which LBFactory class to use.
356 *
357 * @internal For use by ServiceWiring
358 * @param array $config (e.g. $wgLBFactoryConf)
359 * @return string Class name
360 */
361 public function getLBFactoryClass( array $config ): string {
362 $compat = [
363 // For LocalSettings.php compat after removing underscores (since 1.23).
364 'LBFactory_Single' => Wikimedia\Rdbms\LBFactorySingle::class,
365 'LBFactory_Simple' => Wikimedia\Rdbms\LBFactorySimple::class,
366 'LBFactory_Multi' => Wikimedia\Rdbms\LBFactoryMulti::class,
367 // For LocalSettings.php compat after moving classes to namespaces (since 1.29).
368 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
369 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
370 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
371 ];
372
373 $class = $config['class'];
374 return $compat[$class] ?? $class;
375 }
376
377 /**
378 * @param ILBFactory $lbFactory
379 */
380 public function setDomainAliases( ILBFactory $lbFactory ): void {
381 $domain = DatabaseDomain::newFromId( $lbFactory->getLocalDomainID() );
382 // For compatibility with hyphenated $wgDBname values on older wikis, handle callers
383 // that assume corresponding database domain IDs and wiki IDs have identical values
384 $rawLocalDomain = strlen( $domain->getTablePrefix() )
385 ? "{$domain->getDatabase()}-{$domain->getTablePrefix()}"
386 : (string)$domain->getDatabase();
387
388 $lbFactory->setDomainAliases( [ $rawLocalDomain => $domain ] );
389 }
390
391 /**
392 * Apply global state from the current web request or other PHP process.
393 *
394 * This technically violates the principle constraint on ServiceWiring to be
395 * deterministic for a given site configuration. The exemption made here
396 * is solely to aid in debugging and influence non-nominal behaviour such
397 * as ChronologyProtector. That is, the state applied here must never change
398 * the logical destination or meaning of any database-related methods, it
399 * merely applies preferences and debugging information.
400 *
401 * The code here must be non-essential, with LBFactory behaving the same toward
402 * its consumers regardless of whether this is applied or not.
403 *
404 * For example, something may instantiate LBFactory for the current wiki without
405 * calling this, and its consumers must not be able to tell the difference.
406 * Likewise, in the future MediaWiki may instantiate service wiring and LBFactory
407 * for a foreign wiki in the same farm and apply the current global state to that,
408 * and that should be fine as well.
409 *
410 * @param ILBFactory $lbFactory
411 * @param Config $config
412 * @param IBufferingStatsdDataFactory $stats
413 */
414 public function applyGlobalState(
415 ILBFactory $lbFactory,
416 Config $config,
417 IBufferingStatsdDataFactory $stats
418 ): void {
419 if ( MW_ENTRY_POINT === 'cli' ) {
420 $lbFactory->getMainLB()->setTransactionListener(
421 __METHOD__,
422 static function ( $trigger ) use ( $stats, $config ) {
423 // During maintenance scripts and PHPUnit integration tests, we let
424 // DeferredUpdates run immediately from addUpdate(), unless a transaction
425 // is active. Notify DeferredUpdates after any commit to try now.
426 // See DeferredUpdates::tryOpportunisticExecute for why.
427 if ( $trigger === IDatabase::TRIGGER_COMMIT ) {
428 DeferredUpdates::tryOpportunisticExecute();
429 }
430 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
431 MediaWiki::emitBufferedStatsdData( $stats, $config );
432 }
433 );
434 $lbFactory->setWaitForReplicationListener(
435 __METHOD__,
436 static function () use ( $stats, $config ) {
437 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
438 MediaWiki::emitBufferedStatsdData( $stats, $config );
439 }
440 );
441
442 }
443 }
444
445 /**
446 * Log a database deprecation warning
447 *
448 * @param string $msg Deprecation message
449 */
450 public static function logDeprecation( string $msg ): void {
451 if ( isset( self::$loggedDeprecations[$msg] ) ) {
452 return;
453 }
454 self::$loggedDeprecations[$msg] = true;
455 MWDebug::sendRawDeprecated( $msg, true, wfGetCaller() );
456 }
457 }