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