Merge "Add checkDependencies.php"
[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\LBFactory;
27 use Wikimedia\Rdbms\DatabaseDomain;
28
29 /**
30 * MediaWiki-specific class for generating database load balancers
31 * @ingroup Database
32 */
33 abstract class MWLBFactory {
34
35 /** @var array Cache of already-logged deprecation messages */
36 private static $loggedDeprecations = [];
37
38 /**
39 * TODO Make this a const when HHVM support is dropped (T192166)
40 *
41 * @var array
42 * @since 1.34
43 */
44 public static $applyDefaultConfigOptions = [
45 'DBcompress',
46 'DBDefaultGroup',
47 'DBmwschema',
48 'DBname',
49 'DBpassword',
50 'DBport',
51 'DBprefix',
52 'DBserver',
53 'DBservers',
54 'DBssl',
55 'DBtype',
56 'DBuser',
57 'DBWindowsAuthentication',
58 'DebugDumpSql',
59 'DebugLogFile',
60 'ExternalServers',
61 'SQLiteDataDir',
62 'SQLMode',
63 ];
64
65 /**
66 * @param array $lbConf Config for LBFactory::__construct()
67 * @param ServiceOptions $options
68 * @param ConfiguredReadOnlyMode $readOnlyMode
69 * @param BagOStuff $srvCace
70 * @param BagOStuff $mainStash
71 * @param WANObjectCache $wanCache
72 * @return array
73 */
74 public static function applyDefaultConfig(
75 array $lbConf,
76 ServiceOptions $options,
77 ConfiguredReadOnlyMode $readOnlyMode,
78 BagOStuff $srvCace,
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( $serversCheck, $options->get( 'DBname' ),
156 $options->get( 'DBprefix' ) );
157
158 $lbConf = self::injectObjectCaches( $lbConf, $srvCace, $mainStash, $wanCache );
159
160 return $lbConf;
161 }
162
163 /**
164 * @return array
165 */
166 private static function getDbTypesWithSchemas() {
167 return [ 'postgres', 'msssql' ];
168 }
169
170 /**
171 * @param array $server
172 * @param ServiceOptions $options
173 * @return array
174 */
175 private static function initServerInfo( array $server, ServiceOptions $options ) {
176 if ( $server['type'] === 'sqlite' ) {
177 $httpMethod = $_SERVER['REQUEST_METHOD'] ?? null;
178 // T93097: hint for how file-based databases (e.g. sqlite) should go about locking.
179 // See https://www.sqlite.org/lang_transaction.html
180 // See https://www.sqlite.org/lockingv3.html#shared_lock
181 $isHttpRead = in_array( $httpMethod, [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
182 $server += [
183 'dbDirectory' => $options->get( 'SQLiteDataDir' ),
184 'trxMode' => $isHttpRead ? 'DEFERRED' : 'IMMEDIATE'
185 ];
186 } elseif ( $server['type'] === 'postgres' ) {
187 $server += [
188 'port' => $options->get( 'DBport' ),
189 // Work around the reserved word usage in MediaWiki schema
190 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
191 ];
192 } elseif ( $server['type'] === 'oracle' ) {
193 $server += [
194 // Work around the reserved word usage in MediaWiki schema
195 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
196 ];
197 } elseif ( $server['type'] === 'mssql' ) {
198 $server += [
199 'port' => $options->get( 'DBport' ),
200 'useWindowsAuth' => $options->get( 'DBWindowsAuthentication' )
201 ];
202 }
203
204 if ( in_array( $server['type'], self::getDbTypesWithSchemas(), true ) ) {
205 $server += [ 'schema' => $options->get( 'DBmwschema' ) ];
206 }
207
208 $flags = DBO_DEFAULT;
209 $flags |= $options->get( 'DebugDumpSql' ) ? DBO_DEBUG : 0;
210 $flags |= $options->get( 'DebugLogFile' ) ? DBO_DEBUG : 0;
211 if ( $server['type'] === 'oracle' ) {
212 $flags |= $options->get( 'DBOracleDRCP' ) ? DBO_PERSISTENT : 0;
213 }
214
215 $server += [
216 'tablePrefix' => $options->get( 'DBprefix' ),
217 'flags' => $flags,
218 'sqlMode' => $options->get( 'SQLMode' ),
219 ];
220
221 return $server;
222 }
223
224 /**
225 * @param array $lbConf
226 * @param BagOStuff $sCache
227 * @param BagOStuff $mStash
228 * @param WANObjectCache $wCache
229 * @return array
230 */
231 private static function injectObjectCaches(
232 array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
233 ) {
234 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
235 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
236 $lbConf['srvCache'] = $sCache;
237 }
238 if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
239 $lbConf['memStash'] = $mStash;
240 }
241 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
242 $lbConf['wanCache'] = $wCache;
243 }
244
245 return $lbConf;
246 }
247
248 /**
249 * @param array $servers
250 * @param string $ldDB Local domain database name
251 * @param string $ldTP Local domain prefix
252 */
253 private static function assertValidServerConfigs( array $servers, $ldDB, $ldTP ) {
254 foreach ( $servers as $server ) {
255 $type = $server['type'] ?? null;
256 $srvDB = $server['dbname'] ?? null; // server DB
257 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
258
259 if ( $type === 'mysql' ) {
260 // A DB name is not needed to connect to mysql; 'dbname' is useless.
261 // This field only defines the DB to use for unspecified DB domains.
262 if ( $srvDB !== null && $srvDB !== $ldDB ) {
263 self::reportMismatchedDBs( $srvDB, $ldDB );
264 }
265 } elseif ( $type === 'postgres' ) {
266 if ( $srvTP !== '' ) {
267 self::reportIfPrefixSet( $srvTP, $type );
268 }
269 }
270
271 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
272 self::reportMismatchedPrefixes( $srvTP, $ldTP );
273 }
274 }
275 }
276
277 /**
278 * @param string $prefix Table prefix
279 * @param string $dbType Database type
280 */
281 private static function reportIfPrefixSet( $prefix, $dbType ) {
282 $e = new UnexpectedValueException(
283 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
284 "MediaWiki does not support using a table prefix with this RDBMS type."
285 );
286 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
287 exit;
288 }
289
290 /**
291 * @param string $srvDB Server config database
292 * @param string $ldDB Local DB domain database
293 */
294 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
295 $e = new UnexpectedValueException(
296 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
297 "Set \$wgDBname to the database used by this wiki project. " .
298 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
299 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
300 "use of Database::getDomainId(), and other features are not reliable when " .
301 "\$wgDBservers does not match the local wiki database/prefix."
302 );
303 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
304 exit;
305 }
306
307 /**
308 * @param string $srvTP Server config table prefix
309 * @param string $ldTP Local DB domain database
310 */
311 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
312 $e = new UnexpectedValueException(
313 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
314 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
315 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
316 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
317 "use of Database::getDomainId(), and other features are not reliable when " .
318 "\$wgDBservers does not match the local wiki database/prefix."
319 );
320 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
321 exit;
322 }
323
324 /**
325 * Returns the LBFactory class to use and the load balancer configuration.
326 *
327 * @todo instead of this, use a ServiceContainer for managing the different implementations.
328 *
329 * @param array $config (e.g. $wgLBFactoryConf)
330 * @return string Class name
331 */
332 public static function getLBFactoryClass( array $config ) {
333 // For configuration backward compatibility after removing
334 // underscores from class names in MediaWiki 1.23.
335 $bcClasses = [
336 'LBFactory_Simple' => 'LBFactorySimple',
337 'LBFactory_Single' => 'LBFactorySingle',
338 'LBFactory_Multi' => 'LBFactoryMulti'
339 ];
340
341 $class = $config['class'];
342
343 if ( isset( $bcClasses[$class] ) ) {
344 $class = $bcClasses[$class];
345 wfDeprecated(
346 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
347 '1.23'
348 );
349 }
350
351 // For configuration backward compatibility after moving classes to namespaces (1.29)
352 $compat = [
353 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
354 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
355 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
356 ];
357
358 if ( isset( $compat[$class] ) ) {
359 $class = $compat[$class];
360 }
361
362 return $class;
363 }
364
365 /**
366 * @param LBFactory $lbFactory
367 * @param string $dbType 'mysql', 'sqlite', etc.
368 */
369 public static function setSchemaAliases( LBFactory $lbFactory, $dbType ) {
370 if ( $dbType instanceof Config ) {
371 // Before 1.34 this took a whole Config just to get $dbType
372 wfDeprecated( __METHOD__ . ' with Config argument', '1.34' );
373 $dbType = $dbType->get( 'DBtype' );
374 }
375 if ( $dbType === 'mysql' ) {
376 /**
377 * When SQLite indexes were introduced in r45764, it was noted that
378 * SQLite requires index names to be unique within the whole database,
379 * not just within a schema. As discussed in CR r45819, to avoid the
380 * need for a schema change on existing installations, the indexes
381 * were implicitly mapped from the new names to the old names.
382 *
383 * This mapping can be removed if DB patches are introduced to alter
384 * the relevant tables in existing installations. Note that because
385 * this index mapping applies to table creation, even new installations
386 * of MySQL have the old names (except for installations created during
387 * a period where this mapping was inappropriately removed, see
388 * T154872).
389 */
390 $lbFactory->setIndexAliases( [
391 'ar_usertext_timestamp' => 'usertext_timestamp',
392 'un_user_id' => 'user_id',
393 'un_user_ip' => 'user_ip',
394 ] );
395 }
396 }
397
398 /**
399 * Log a database deprecation warning
400 * @param string $msg Deprecation message
401 */
402 public static function logDeprecation( $msg ) {
403 global $wgDevelopmentWarnings;
404
405 if ( isset( self::$loggedDeprecations[$msg] ) ) {
406 return;
407 }
408 self::$loggedDeprecations[$msg] = true;
409
410 if ( $wgDevelopmentWarnings ) {
411 trigger_error( $msg, E_USER_DEPRECATED );
412 }
413 wfDebugLog( 'deprecated', $msg, 'private' );
414 }
415 }