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