Merge "build: Lower default Karma logLevel during local development"
[lhc/web/wiklou.git] / includes / db / MWLBFactory.php
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 MediaWiki\Config\ServiceOptions;
25 use MediaWiki\Logger\LoggerFactory;
26 use Wikimedia\Rdbms\DatabaseDomain;
27
28 /**
29 * MediaWiki-specific class for generating database load balancers
30 * @ingroup Database
31 */
32 abstract class MWLBFactory {
33
34 /** @var array Cache of already-logged deprecation messages */
35 private static $loggedDeprecations = [];
36
37 /**
38 * TODO Make this a const when HHVM support is dropped (T192166)
39 *
40 * @var array
41 * @since 1.34
42 */
43 public static $applyDefaultConfigOptions = [
44 'DBcompress',
45 'DBDefaultGroup',
46 'DBmwschema',
47 'DBname',
48 'DBpassword',
49 'DBport',
50 'DBprefix',
51 'DBserver',
52 'DBservers',
53 'DBssl',
54 'DBtype',
55 'DBuser',
56 'DBWindowsAuthentication',
57 'DebugDumpSql',
58 'DebugLogFile',
59 'ExternalServers',
60 'SQLiteDataDir',
61 'SQLMode',
62 ];
63
64 /**
65 * @param array $lbConf Config for LBFactory::__construct()
66 * @param ServiceOptions $options
67 * @param ConfiguredReadOnlyMode $readOnlyMode
68 * @param BagOStuff $srvCache
69 * @param BagOStuff $mainStash
70 * @param WANObjectCache $wanCache
71 * @return array
72 * @internal For use with service wiring
73 */
74 public static function applyDefaultConfig(
75 array $lbConf,
76 ServiceOptions $options,
77 ConfiguredReadOnlyMode $readOnlyMode,
78 BagOStuff $srvCache,
79 BagOStuff $mainStash,
80 WANObjectCache $wanCache
81 ) {
82 $options->assertRequiredOptions( self::$applyDefaultConfigOptions );
83
84 global $wgCommandLineMode;
85
86 $typesWithSchema = self::getDbTypesWithSchemas();
87
88 $lbConf += [
89 'localDomain' => new DatabaseDomain(
90 $options->get( 'DBname' ),
91 $options->get( 'DBmwschema' ),
92 $options->get( 'DBprefix' )
93 ),
94 'profiler' => function ( $section ) {
95 return Profiler::instance()->scopedProfileIn( $section );
96 },
97 'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
98 'replLogger' => LoggerFactory::getInstance( 'DBReplication' ),
99 'queryLogger' => LoggerFactory::getInstance( 'DBQuery' ),
100 'connLogger' => LoggerFactory::getInstance( 'DBConnection' ),
101 'perfLogger' => LoggerFactory::getInstance( 'DBPerformance' ),
102 'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
103 'deprecationLogger' => [ static::class, 'logDeprecation' ],
104 'cliMode' => $wgCommandLineMode,
105 'hostname' => wfHostname(),
106 'readOnlyReason' => $readOnlyMode->getReason(),
107 'defaultGroup' => $options->get( 'DBDefaultGroup' ),
108 ];
109
110 $serversCheck = [];
111 // When making changes here, remember to also specify MediaWiki-specific options
112 // for Database classes in the relevant Installer subclass.
113 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
114 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
115 if ( isset( $lbConf['servers'] ) ) {
116 // Server array is already explicitly configured
117 } elseif ( is_array( $options->get( 'DBservers' ) ) ) {
118 $lbConf['servers'] = [];
119 foreach ( $options->get( 'DBservers' ) as $i => $server ) {
120 $lbConf['servers'][$i] = self::initServerInfo( $server, $options );
121 }
122 } else {
123 $server = self::initServerInfo(
124 [
125 'host' => $options->get( 'DBserver' ),
126 'user' => $options->get( 'DBuser' ),
127 'password' => $options->get( 'DBpassword' ),
128 'dbname' => $options->get( 'DBname' ),
129 'type' => $options->get( 'DBtype' ),
130 'load' => 1
131 ],
132 $options
133 );
134
135 $server['flags'] |= $options->get( 'DBssl' ) ? DBO_SSL : 0;
136 $server['flags'] |= $options->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
137
138 $lbConf['servers'] = [ $server ];
139 }
140 if ( !isset( $lbConf['externalClusters'] ) ) {
141 $lbConf['externalClusters'] = $options->get( 'ExternalServers' );
142 }
143
144 $serversCheck = $lbConf['servers'];
145 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
146 if ( isset( $lbConf['serverTemplate'] ) ) {
147 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
148 $lbConf['serverTemplate']['schema'] = $options->get( 'DBmwschema' );
149 }
150 $lbConf['serverTemplate']['sqlMode'] = $options->get( 'SQLMode' );
151 }
152 $serversCheck = [ $lbConf['serverTemplate'] ] ?? [];
153 }
154
155 self::assertValidServerConfigs(
156 $serversCheck,
157 $options->get( 'DBname' ),
158 $options->get( 'DBprefix' )
159 );
160
161 $lbConf = self::injectObjectCaches( $lbConf, $srvCache, $mainStash, $wanCache );
162
163 return $lbConf;
164 }
165
166 /**
167 * @return array
168 */
169 private static function getDbTypesWithSchemas() {
170 return [ 'postgres' ];
171 }
172
173 /**
174 * @param array $server
175 * @param ServiceOptions $options
176 * @return array
177 */
178 private static function initServerInfo( array $server, ServiceOptions $options ) {
179 if ( $server['type'] === 'sqlite' ) {
180 $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
181 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
182 // See https://www.sqlite.org/lang_transaction.html
183 // See https://www.sqlite.org/lockingv3.html#shared_lock
184 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
185 $server += [
186 'dbDirectory' => $options->get( 'SQLiteDataDir' ),
187 'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
188 ];
189 } elseif ( $server['type'] === 'postgres' ) {
190 $server += [
191 'port' => $options->get( 'DBport' ),
192 // Work around the reserved word usage in MediaWiki schema
193 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
194 ];
195 }
196
197 if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
198 $server += [ 'schema' => $options->get( 'DBmwschema' ) ];
199 }
200
201 $flags = DBO_DEFAULT;
202 $flags |= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG : 0;
203 $flags |= $options->get( 'DebugLogFile' ) ? DBO_DEBUG : 0;
204
205 $server += [
206 'tablePrefix' => $options->get( 'DBprefix' ),
207 'flags' => $flags,
208 'sqlMode' => $options->get( 'SQLMode' ),
209 ];
210
211 return $server;
212 }
213
214 /**
215 * @param array $lbConf
216 * @param BagOStuff $sCache
217 * @param BagOStuff $mStash
218 * @param WANObjectCache $wCache
219 * @return array
220 */
221 private static function injectObjectCaches(
222 array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
223 ) {
224 // Fallback if APC style caching is not an option
225 if ( $sCache instanceof EmptyBagOStuff ) {
226 $sCache = new HashBagOStuff( [ 'maxKeys' => 100 ] );
227 }
228
229 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
230 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
231 $lbConf['srvCache'] = $sCache;
232 }
233 if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
234 $lbConf['memStash'] = $mStash;
235 }
236 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
237 $lbConf['wanCache'] = $wCache;
238 }
239
240 return $lbConf;
241 }
242
243 /**
244 * @param array $servers
245 * @param string $ldDB Local domain database name
246 * @param string $ldTP Local domain prefix
247 */
248 private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
249 foreach ( $servers as $server ) {
250 $type = $server['type'] ?? null;
251 $srvDB = $server['dbname'] ?? null; // server DB
252 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
253
254 if ( $type === 'mysql' ) {
255 // A DB name is not needed to connect to mysql; 'dbname' is useless.
256 // This field only defines the DB to use for unspecified DB domains.
257 if ( $srvDB !== null && $srvDB !== $ldDB ) {
258 self::reportMismatchedDBs( $srvDB, $ldDB );
259 }
260 } elseif ( $type === 'postgres' ) {
261 if ( $srvTP !== '' ) {
262 self::reportIfPrefixSet( $srvTP, $type );
263 }
264 }
265
266 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
267 self::reportMismatchedPrefixes( $srvTP, $ldTP );
268 }
269 }
270 }
271
272 /**
273 * @param string $prefix Table prefix
274 * @param string $dbType Database type
275 */
276 private static function reportIfPrefixSet( $prefix, $dbType ) {
277 $e = new UnexpectedValueException(
278 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
279 "MediaWiki does not support using a table prefix with this RDBMS type."
280 );
281 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
282 exit;
283 }
284
285 /**
286 * @param string $srvDB Server config database
287 * @param string $ldDB Local DB domain database
288 */
289 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
290 $e = new UnexpectedValueException(
291 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
292 "Set \$wgDBname to the database used by this wiki project. " .
293 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
294 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
295 "use of Database::getDomainId(), and other features are not reliable when " .
296 "\$wgDBservers does not match the local wiki database/prefix."
297 );
298 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
299 exit;
300 }
301
302 /**
303 * @param string $srvTP Server config table prefix
304 * @param string $ldTP Local DB domain database
305 */
306 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
307 $e = new UnexpectedValueException(
308 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
309 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
310 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
311 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
312 "use of Database::getDomainId(), and other features are not reliable when " .
313 "\$wgDBservers does not match the local wiki database/prefix."
314 );
315 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
316 exit;
317 }
318
319 /**
320 * Returns the LBFactory class to use and the load balancer configuration.
321 *
322 * @todo instead of this, use a ServiceContainer for managing the different implementations.
323 *
324 * @param array $config (e.g. $wgLBFactoryConf)
325 * @return string Class name
326 * @internal For use with service wiring
327 */
328 public static function getLBFactoryClass( array $config ) {
329 // For configuration backward compatibility after removing
330 // underscores from class names in MediaWiki 1.23.
331 $bcClasses = [
332 'LBFactory_Simple' => 'LBFactorySimple',
333 'LBFactory_Single' => 'LBFactorySingle',
334 'LBFactory_Multi' => 'LBFactoryMulti'
335 ];
336
337 $class = $config['class'];
338
339 if ( isset( $bcClasses[$class] ) ) {
340 $class = $bcClasses[$class];
341 wfDeprecated(
342 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
343 '1.23'
344 );
345 }
346
347 // For configuration backward compatibility after moving classes to namespaces (1.29)
348 $compat = [
349 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
350 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
351 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
352 ];
353
354 if ( isset( $compat[$class] ) ) {
355 $class = $compat[$class];
356 }
357
358 return $class;
359 }
360
361 /**
362 * Log a database deprecation warning
363 * @param string $msg Deprecation message
364 * @internal For use with service wiring
365 */
366 public static function logDeprecation( $msg ) {
367 global $wgDevelopmentWarnings;
368
369 if ( isset( self::$loggedDeprecations[$msg] ) ) {
370 return;
371 }
372 self::$loggedDeprecations[$msg] = true;
373
374 if ( $wgDevelopmentWarnings ) {
375 trigger_error( $msg, E_USER_DEPRECATED );
376 }
377 wfDebugLog( 'deprecated', $msg, 'private' );
378 }
379 }